How to read a newline character in c

Can 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 line as the user input,

 #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?

+4
source share
2 answers

Did you literally type \ , then n ?

If so, he literally placed \ , and then n on your line, as if you had done the following:

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

This is logically not a newline, but rather <<20> followed by n .

If you want to support escape sequences in user input, you will need to process any user input to create the appropriate sequence output.

 /* 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; 
+4
source

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

+2
source

All Articles