Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape the % (percent) sign in C's printf

How do you escape the % sign when using printf in C?

printf("hello\%"); /* not like this */ 
like image 261
Chris_45 Avatar asked Dec 07 '09 14:12

Chris_45


2 Answers

You can escape it by posting a double '%' like this: %%

Using your example:

printf("hello%%"); 

Escaping the '%' sign is only for printf. If you do:

char a[5]; strcpy(a, "%%"); printf("This is a's value: %s\n", a); 

It will print: This is a's value: %%

like image 129
Pablo Santa Cruz Avatar answered Oct 21 '22 22:10

Pablo Santa Cruz


As others have said, %% will escape the %.

Note, however, that you should never do this:

char c[100]; char *c2; ... printf(c); /* OR */ printf(c2); 

Whenever you have to print a string, always, always, always print it using

printf("%s", c) 

to prevent an embedded % from causing problems (memory violations, segmentation faults, etc.).

like image 20
Mikeage Avatar answered Oct 22 '22 00:10

Mikeage