是否有一种简单的方法可以转义 printf()
函数中的所有特殊字符?
我想知道如何执行此操作的原因是因为我正在打印许多字符,其中可能包括特殊字符,例如空字符(\0
)和蜂鸣字符以及我只想查看字符串的内容。
目前我正在使用以下代码
它适用于空字符。转义所有特殊字符的最简单方法是什么?
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 ] ) );
}
最佳答案
首先,'\\0'
是一个两个字符的文字,它实际上应该是一个两个字符的字符串。至于将所有特殊字符打印为转义码,您还需要一些代码:
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;
}
关于c++ - 转义 printf() 中的所有特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22150946/