1

I want to convert a percentage to a string via sprintf. A workable way is like this:

sprintf(str, "%d", num);
strcat(str, "%");

But is there a way to only use sprintf to make it done?

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Tom Xue
  • 3,169
  • 7
  • 40
  • 77
  • 5
    `sprintf(str, "%d%%", num);`? –  Oct 13 '16 at 04:49
  • 1
    Always consult the [man page](https://linux.die.net/man/3/sprintf): "A '%' is written. No argument is converted. The complete conversion specification is '%%'" – kaylum Oct 13 '16 at 04:50
  • Possible duplicate of [How to escape the % sign in C's printf?](https://stackoverflow.com/questions/1860159/how-to-escape-the-sign-in-cs-printf) – nwellnhof Oct 01 '17 at 12:26

1 Answers1

0

(Compiling an answer from comments, just to get this out of the list of unanswered questions.)

Printing a % via sprintf() is done via "%%", i.e. in your case thus:

sprintf(str, "%d%%", num);

Here is a quote from the helpful documentation:

A '%' is written. No argument is converted. The complete conversion specification is '%%'

Yunnosch
  • 26,130
  • 9
  • 42
  • 54