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.
#includeusing namespace std; int main() { printf("You got 80% in Exam"); return 0; }
Output
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:
#includeusing 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
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.
#includeusing namespace std; int main() { puts("You got 80% in Exam"); return 0; }
Output
You got 80% in Exam
That’s all about how to escape percent sign in printf Method in C++.