Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

printf

This piece of code is acting a bit strange to my taste. Please, anyone care to explain why? And how to force '\n' to 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;
}

Bottom line, the intention is that the 2nd string to be printed in two lines, just like the first. This program is a simplification. The real program has problems reading from a file using fgets (not a S.O. argument to argv like here), but I think solving here will also solve there.

like image 732
DrBeco Avatar asked Nov 09 '22 16:11

DrBeco


1 Answers

It seems the shell doesn't recognize and convert the "escape sequence". Use a shell software that supports \n escape sequence.

like image 141
MikeCAT Avatar answered Nov 15 '22 04:11

MikeCAT