Escape all special characters in printf()

前端 未结 4 1570
遇见更好的自我
遇见更好的自我 2020-12-07 04:24

Is there an easy way to escape all special characters in the printf() function?

The reason why I would like to know how to do this is because I am print

4条回答
  •  时光取名叫无心
    2020-12-07 05:17

    First of all, '\\0' is a two-character literal, which should really be a two-character string. As for printing all special characters as escape code, you need some more code:

    switch (data[i])
    {
    case '\0':
        printf("\\0");
        break;
    case '\n':
        printf("\\n");
        break;
    
    /* Etc. */
    
    default:
        /* Now comes the "hard" part, because not all characters here
         * are actually printable
         */
        if (isprint(data[i]))
            printf("%c", data[i]);  /* Printable character, print it as usual */
        else
            printf("\\x%02x", data[i]); /* Non-printable character, print as hex value */
    
        break;
    }
    

提交回复
热议问题