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

前端 未结 13 2874
长发绾君心
长发绾君心 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:29

    If there are no formats in the string, you can use puts (or fputs):

    puts("hello%");
    

    if there is a format in the string:

    printf("%.2f%%", 53.2);
    

    As noted in the comments, puts appends a \n to the output and fputs does not.

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

    Like this:

    printf("hello%%");
    //-----------^^ inside printf, use two percent signs together
    
    0 讨论(0)
  • 2020-11-22 10:31

    You can use %%:

    printf("100%%");
    

    The result is:

    100%

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

    you are using incorrect format specifier you should use %% for printing %. Your code should be:

    printf("hello%%");  
    

    Read more all format specifiers used in C.

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

    Yup, use printf("hello%%"); and it's done.

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

    With itself...

    printf("hello%%"); /* like this */
    
    0 讨论(0)
提交回复
热议问题