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

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

c++ - 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 () 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

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

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...