Interpretation of '\ n' in printf ("% s", string)

This piece of code acts a little strange for my taste. Please, does anyone want to explain why? And how to make "\ n" be interpreted as a special char?

beco@raposa :~/tmp/user/foo/bar$ ./interpretastring.x "2nd\nstr" 1st str 2nd\nstr beco@raposa :~/tmp/user/foo/bar$ cat interpretastring.c #include <stdio.h> int main(int argc, char **argv) { char *s="1st\nstr"; printf("%s\n", s); printf("%s\n", argv[1]); return 0; } 

In the bottom line, it is assumed that the second line will be printed in two lines, like the first. This program is a simplification. The real program has problems reading from a file using fgets (rather than the SO argument for argv , as here), but I think the solution here will also solve there.

+5
source share
2 answers

For all purposes, this will just be taken care of \n and no other characters will receive special treatment.

This answer here does the job with less complexity. It does not change "2 characters" to "one special \n ". It just changes <\><n> to " <space><newline> ". It's great. It would be better if there was a C Standard Library interpret special chars in a string (as I know, it has one for RegExp ).

 /* change '\\n' into ' \n' */ void changebarn(char *nt) { while(nt!=NULL) if((nt=strchr(nt,'\\'))) if(*++nt=='n') { *nt='\n'; *(nt-1)=' '; } } 
0
source

The shell does not seem to recognize or convert the escape sequence. Use shell software that supports the escape sequence \n .

+1
source

Source: https://habr.com/ru/post/1247083/


All Articles