Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 () 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 ] ) );
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
268 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 '':
    printf("\0");
    break;
case '
':
    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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...