Question

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?

Was it helpful?

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.

OTHER TIPS

There is only one expansion during printf; that means any strings passed to printf except the format strings will be printed verbatim (if at all). That is actually a good thing, because otherwise, it leaves a huge security hole.

The security risk relates to the fact that the format string and the parameter list have to correspond. That means, if an unwanted % makes it to the format string, you will get in trouble:

char ch[50];
fgets(ch, 50, stdin);
printf(ch);

If the user supplies eg. %p %p %p %p, he will be reading data stored on the stack (like the return address and so on), if he supplies %s %s %s, he'll likely crash the program. If he supplies %n, he'll overwrite some data on the stack.

That said, you can just compute the format string if you want:

char ch[50];
char format_prototype[]="My name is %s";
snprintf(ch, 49, "%s", format_prototype);
ch[49]=0;
printf(ch, "Tom");

printf(string, "Tom") maybe?

The problem is with printf("%s",string,"Tom"); line You should use

char string[]="My name is %s";
printf(string,"Tom");

here you will get the output as

My name is Tom

The first parameter to printf is the format string. The rest are all parameters which will be formatted according to the format string. The format strings do not nest in any way. In other words, even if a string to be formatted happens to contain formatting instruction, it is simply printed and not interpreted as another format string.

If you want to have that kind of formatting indirection, you would have to first generate a new format string (sprintf is useful for that):

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

sprintf(format, "%s", string);

and then use the newly generated format string:

printf(format, "Tom");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top