DrBeco
DrBeco

Reputation: 11785

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

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.

Upvotes: 5

Views: 671

Answers (2)

DrBeco
DrBeco

Reputation: 11785

For all purposes, this just take care of \n and no other characters get special treatment.

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

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

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

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

Upvotes: 1

Related Questions