Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the "%" character with printf [duplicate]

Tags:

c++

c

The output of

printf("%%%%%%%%");

is

%%%%

I used % eight times. Why does the output only have four %s?

like image 690
nitin kumar Avatar asked Dec 01 '22 15:12

nitin kumar


2 Answers

Because % is a format specifier escape sequence (as in %d would print an int).

To get the program to print the actual symbol, you write %%. The same goes for \ (although fundamentally different, you still need to to print one).

like image 177
Luchian Grigore Avatar answered Dec 09 '22 21:12

Luchian Grigore


The "%" is a special character, and it's used to specify format specifiers. To print a literal "%", you need a sequence of two "%%".

The "%" is used in the format string to specify a placeholder that will be replaced by a corresponding argument passed to the functions that format their output, like printf()/fprintf()/sprintf().

So how can you print a literal "%"?

  • Escaping it with another "%".

If you for example wish to print an integral percentage value, you need to specify as the "%d" the format specifier and a literal "%", so you would do it this way:

printf("%d%%\n", value):

Read this to learn more about it.

like image 27
Iharob Al Asimi Avatar answered Dec 09 '22 21:12

Iharob Al Asimi