Search code examples
cformat-specifiers

Format specifiers in C - %s inside %s


I have something like this

char string[]="My name is %s";

printf("%s",string,"Tom");

I expect the output to be My name is Tom but I am getting My name is %s

I tried escaping the % character, but it dint work.

What's going wrong here? How shall I have a %s inside a %s?


Solution

  • Try something like this

    printf(string,"Tom");
    

    The problem with your method is this -

    As soon as printf sees %s format specifier in your format string, it assumes that the next argument in list is a string pointed to by a character pointer, retrieves it and prints it in place of %s. Now, printf doesn't do a recursive replacement and hence %s inside your string remains as it is and "Tom" is now an extra argument which is just discarded.