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 ] ) );
}
Use the
isprint
library function to determine if the character is printable:In case code needs to write with no ambiguity, using C syntax:
Alternatively, code could
To use a hexadecimal-escape-sequence or a shorten octal-escape-sequence, code needs to insure that the next character does not create ambiguity. That complication does not occur in the above code as it uses 3-digit octal-escape-sequences. Amended code would be something like:
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: