C语言 如何将转义字符打印为字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6684976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i print escape characters as characters?
提问by user798774
I'm trying to print escape characters as characters or strings using this code:
我正在尝试使用以下代码将转义字符打印为字符或字符串:
while((c = fgetc(fp))!= EOF)
{
if(c == 'switch (c) {
case 'const char *ecs[256] = {NULL}; // assumes ASCII - may not be a valid assumption
int c;
ecs['if(c == 'printf("%%d");
')
{
printf(" \0");
}
else if(c == '\a')
{
printf(" \a");
}
else if(c == '\b')
{
printf(" \b");
}
else if(c == '\f')
{
printf(" \f");
}
else if(c == '\n')
{
printf(" \n");
}
else if(c == '\r')
{
printf(" \r");
}
else if(c == '\t')
{
printf(" \t");
}
else if(c == '\v')
{
printf(" \v");
}
'] = "\0";
ecs['\a'] = "\a";
ecs['\b'] = "\b";
...
while ((c = fgetc(fp)) != EOF)
{
if (ecs[c] == NULL)
printf("%c", c);
else
printf("%s", ecs[c]);
}
':
printf(" \0");
break;
case '\a':
printf(" \a");
break;
/* And so on. */
}
')
{
printf(" ##代码##");
}
else if(c == '\a')
{
printf(" \a");
}
else if(c == '\b')
{
printf(" \b");
}
else if(c == '\f')
{
printf(" \f");
}
else if(c == '\n')
{
printf(" \n");
}
else if(c == '\r')
{
printf(" \r");
}
else if(c == '\t')
{
printf(" \t");
}
else if(c == '\v')
{
printf(" \v");
}
}
but when i try it, it actually prints the escape sequence.
但是当我尝试它时,它实际上打印了转义序列。
回答by cnicutar
Escape the slashes (use " \\a") so they won't get interpreted specially. Also you might want to use a lookup table or a switchat least.
转义斜杠(使用" \\a"),这样它们就不会被特别解释。此外,您可能想要使用查找表或switch至少使用查找表。
回答by John Bode
Backslashes in string literals need to be escaped; instead of "\0", you need "\\0".
字符串文字中的反斜杠需要转义;而不是"\0",你需要"\\0"。
A lookup table might make this less painful:
查找表可能会使这变得不那么痛苦:
##代码##Yes, the majority of entries in ecsare going to be NULL; the tradeoff is that I don't have to worry about mapping the character value to array index.
是的,大多数条目ecs将是 NULL;权衡是我不必担心将字符值映射到数组索引。
回答by aibk01
For that we need to use double backslash.
为此,我们需要使用双反斜杠。
Examples:
例子:
##代码##Should work for you!
应该为你工作!
回答by dave tumbledrier
If you want to escape %dwithin printfto allow you to actually print the characters "%d":
如果你想逃避%d之内printf,让您可以实际打印字符“%d”:

