tags:

views:

223

answers:

5

I want to print "%SomeString%" in C.

Is this correct?

printf("%%s%",SomeString);
+7  A: 

No.

Use %%%s%%

Pavel Radzivilovsky
explanation: %% escapes to a % character. %s is a control code.
Pavel Radzivilovsky
+19  A: 

No, %% outputs %, so the right syntax is:

printf("%%%s%%",string);
Max
+1: Word for word what I had in the answer box. :)
sdolan
A: 

Hi,

You can print a string like this: printf("%s", SomeString);

It should work!

Daniel
The point was to output % sign at left and at right of the formatted string.
Max
Oh ok, thought he made a mistake in the post!
Daniel
+3  A: 

This solution absolves you from knowing how special printf characters like '%' or '\' should be printed.

#include <stdio.h>

int main(void)
{
    const char str[]="MyString";
    printf("%c%s%c",'%',str,'%');
    return 0;
}
Iulian Şerbănoiu
Isn't that a bit overkilling? `printf` has an appropriate escape charachter for `%` so why not using it? If the problem is remembering it... well, it's just a Google search away.
nico
Don't get me wrong, I wouldn't use this if I knew the %% or \\ sequences but it's still good to know in my opinion.
Iulian Şerbănoiu
Yeah, its good to realize you can do this. I think it would help people understand what printf is doing. But don't do it in production. :)
BobbyShaftoe
@BobbyShaftoe you are correct - it pushes more elements that it should on the stack, it keeps memory occupied with the parameters ('%', '%'are constants that must be held in memory before being pushed on the stack for the *printf functions)
Iulian Şerbănoiu
+5  A: 
printf("%%%s%%", string);

Should output a % each side.