In this post, we will see how to escape percent sign in printf Method in C++.
Escape percent sign in Printf Method in C++
printf()
method uses percent sign(%
) as prefix of format specifier.
For example:
To use number in prinf()
method, we use %d, but what if you actually want to use percent sign in the String.
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> using namespace std; int main() { printf("You got 80% in Exam"); return 0; } |
Output
1 2 3 4 5 6 7 8 9 |
main.cpp: In function ‘int main()’: main.cpp:15:25: warning: format ‘%i’ expects a matching ‘int’ argument [-Wformat=] 15 | printf("You got 80% in Exam"); | ~~^ | | | int You got 80 1133276632n Exam |
As you can see, it didn’t print output as expected.
If you want to escape percent sign in printf()
method, you can use % twice (%%
).
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> using namespace std; int main() { printf("You got 80%% in Exam"); // With % specifier for float printf("You got %.f%% in Exam", 87.25); return 0; } |
Output
1 2 3 4 |
You got 80% in Exam You got 87.25% in Exam |
Further reading:
If you don’t require any formats in String, you can use puts
or fputs
as well.
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> using namespace std; int main() { puts("You got 80% in Exam"); return 0; } |
Output
1 2 3 |
You got 80% in Exam |
That’s all about how to escape percent sign in printf Method in C++.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.