Search code examples
c++ccharescapingprintf

Escape all special characters in printf()


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 printing a number of characters which may include special characters such as the null character (\0) and the beep character and I just want to see the contents of the string.

Currently I am using the following code

It works for null characters. What would be the easiest way to escape all special characters?

int length;
char* data = GetData( length ); // Fills the length as reference

for( int i = 0;  i < length;  i++ )
{
    char c = data[ i ];
    printf( "%c", ( c == 0  ?  '\\0'  :  data[ i ] ) );
}

Solution

  • 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%02hhx", (unsigned char) data[i]); /* Non-printable character, print as hex value */
    
        break;
    }