-2

So I want to check if someone enters: \n ('\' and then 'n') from the keyboard to a string, so I'm doing something like this:

if ( ((str[i] == '\') && (str[i+1] == 'n')) ) {
    //...
}

However this doesn't work because it recognizes \ as an escape character and the whole thing breaks.

Any better way to do this ?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Xaloni
  • 1
  • 3
  • 6
    Public service announcement: We don't need 20 (similar) answers on a simple question like this. – HamZa Dec 18 '14 at 10:04
  • 3
    @HamZa: especially when (.. counting) exactly *half* seem to focus on precisely the wrong thing. – Jongware Dec 18 '14 at 10:09
  • 1
    @Xaloni if this doesn't work, you may comment the answer that gave you this and maybe edit your question to explain *why* it doesn't work (what does it do and why this is not what you want). – Dettorer Dec 18 '14 at 10:14
  • possible duplicate of [How do i print escape characters as characters?](http://stackoverflow.com/questions/6684976/how-do-i-print-escape-characters-as-characters) – jww Dec 22 '14 at 07:55

6 Answers6

5

You have to escape \ by doubling it:

if ( ((str[i] == '\\') && (str[i+1] == 'n')) ){
}
daouzli
  • 15,288
  • 1
  • 18
  • 17
2

The escape sequence for an actual backslash is \\, e.g.

char c = getchar();
if(c == '\\')
    ... stuff ...
slugonamission
  • 9,562
  • 1
  • 34
  • 41
1

compare the \ like this. if ((str[i] == '\\') && (str[i+1] == 'n'))

because we have to escape the escape sequence \.

sharon
  • 734
  • 6
  • 15
0

Instead of escape characters you can use the ASCII values like this

  if ((str[i] == 92) && (str[i+1] == 'n'))
        ;
Bhuvanesh
  • 1,269
  • 1
  • 15
  • 25
0

you use another \

    if ( str[i] == '\\' && str[i+1] == 'n');
Rajalakshmi
  • 681
  • 5
  • 17
  • This *answer* would be SO MUCH better if you added a sentence explaining escape cnd reserved characters. –  Dec 18 '14 at 11:56
  • That would be the second one trying to explain rather than just saying "You have to.", Himanshu's answer added a quick explanation but got downvoted for some reason. – Dettorer Dec 18 '14 at 12:01
-1

if user enter like \ and n using keyboard .

then try like this

 if(str[i] == '\\' && str[i+1] == 'n')

As \ is represented by \\, so use \\ instead of \ to check.

Himanshu
  • 4,327
  • 16
  • 31
  • 39