How to escape the % (percent) sign in C's printf?

前端 未结 13 2835
长发绾君心
长发绾君心 2020-11-22 09:34

How do you escape the % sign when using printf in C?

printf(\"hello\\%\"); /* not like this */
相关标签:
13条回答
  • 2020-11-22 10:14

    As others have said, %% will escape the %.

    Note, however, that you should never do this:

    char c[100];
    char *c2;
    ...
    printf(c); /* OR */
    printf(c2);
    

    Whenever you have to print a string, always, always, always print it using

    printf("%s", c)
    

    to prevent an embedded % from causing problems [memory violations, segfault, etc]

    0 讨论(0)
  • 2020-11-22 10:14

    The backslash in C is used to escape characters in strings. Strings would not recognize % as a special character, and therefore no escape would be necessary. printf is another matter: use %% to print one %.

    0 讨论(0)
  • 2020-11-22 10:19

    The double '%' works also in ".Format(…). Example (with iDrawApertureMask == 87, fCornerRadMask == 0.05): csCurrentLine.Format("\%ADD%2d%C,%6.4f*\%",iDrawApertureMask,fCornerRadMask) ; gives the desired and expected value of (string contents in) csCurrentLine; "%ADD87C, 0.0500*%"

    0 讨论(0)
  • 2020-11-22 10:20

    You can escape it by posting a double '%' like this: %%

    Using your example:

    printf("hello%%");
    

    Escaping '%' sign is only for printf. If you do:

    char a[5];
    strcpy(a, "%%");
    printf("This is a's value: %s\n", a);
    

    It will print: This is a's value: %%

    0 讨论(0)
  • 2020-11-22 10:20

    You can simply use % twice, that is "%%"

    Example:

    printf("You gave me 12.3 %% of profit");
    
    0 讨论(0)
  • 2020-11-22 10:24

    Nitpick:
    You don't really escape the % in the string that specifies the format for the printf() (and scanf()) family of functions.

    The %, in the printf() (and scanf()) family of functions, starts a conversion specification. One of the rules for conversion specification states that a % as a conversion specifier (immediately following the % that started the conversion specification) causes a '%' character to be written with no argument converted.

    The string really has 2 '%' characters inside (as opposed to escaping characters: "a\bc" is a string with 3 non null characters; "a%%b" is a string with 4 non null characters).

    0 讨论(0)
提交回复
热议问题