Escape Percent Sign in printf Method in C++

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.

#include 
using 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:

#include 
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

You got 80% in Exam
You got 87.25% in Exam

If you don’t require any formats in String, you can use puts or fputs as well.

#include 
using 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++.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.