4

Could someone explain the following codes

#include<stdio.h>
main()
{
    char c[]="abc\nabc";
    puts(c);
}

This code as expected generates :

abc
abc

But when i try to take the same string as an input from the user,

#include<stdio.h>
main()
{
    char c[]="abc\nabc";
    gets(c);             // i type in "abc\nabc" 
    puts(c);
}

This code generates :

abc\nabc

How can i make the program read the newline character correctly ?

Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70
  • 3
    FYI: [**Never** use `gets`; use `fgets` instead](http://stackoverflow.com/questions/3302255/c-scanf-vs-gets-vs-fgets). – Oliver Charlesworth Jan 11 '13 at 04:04
  • 2
    @dicarlo2 - [Because it is very, very unsafe](http://stackoverflow.com/questions/2973985/why-gets-is-not-working). –  Jan 11 '13 at 04:14
  • @OliCharlesworth Thanks for the link! That's something I definitely did not remember since the last time I've written in C/C++. – Alex DiCarlo Jan 11 '13 at 04:16

2 Answers2

4

Did you literally type \ then n?

If so, it literally placed a \ and then a n in your string, as if you did the following:

char c[] = "abc\\nabc"; /* note the escaped \ */

This is logically not a newline character, but rather a \ followed by a n.

If you would like to support escape sequences in user input, you'll need to post-process any user input to create the appropriate escape sequences.

/* translate escape sequences inline */
for (i = 0, j = 0; c[i] != 0; ++i, ++j) {
   if (c[i] == '\\' && c[i+1] != 0) {
       switch(c[++i]) {
       case 'n':  c[j] = '\n'; break;
       case '\\': c[j] = '\\'; break;
       /* add the others you'd like to handle here */
       /* case 'a': ... */
       default:   c[j] = ' ';  break;
       }
   } else {
       c[j] = c[i];
   }
}

c[j] = 0;
user7116
  • 63,008
  • 17
  • 141
  • 172
  • I dont get you. How can a single char variable c[i] hold two characters (\\\) – sr01853 Jan 11 '13 at 04:22
  • 1
    @Sibi: `'\\'` is one character. – Dietrich Epp Jan 11 '13 at 04:24
  • Thanks ! Solved my problem. But how come this code 'char c[]="abc\nabc";' stores '\n' as a single character ? – Ankit Rustagi Jan 11 '13 at 07:43
  • 1
    Because `"\n"` is the escape sequence for a new line which your **compiler** turns into the appropriate single code point (or wide code point depending on settings). Your console/shell/TTY/text file does not know or care about C escape sequences. – user7116 Jan 11 '13 at 13:40
2

In string literal or as a char const, '\n' is one character where \ is called escape character. But as inputs, '\' is one real character and not a escape character.

thetaprime
  • 356
  • 4
  • 11