如何将转义字符打印为字符?
我正在尝试使用此代码将转义字符打印为字符或字符串:
while((c = fgetc(fp))!= EOF)
{
if(c == '\0')
{
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");
}
}
但是当我尝试时,它实际上打印了转义序列。
I'm trying to print escape characters as characters or strings using this code:
while((c = fgetc(fp))!= EOF)
{
if(c == '\0')
{
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");
}
}
but when i try it, it actually prints the escape sequence.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为此,我们需要使用双反斜杠。
示例:
应该适合你!
For that we need to use double backslash.
Examples:
Should work for you!
如果您想在
printf
中转义%d
以允许实际打印字符“%d”:If you want to escape
%d
withinprintf
to allow you to actually print the characters "%d":转义斜杠(使用
" \\a"
),这样它们就不会被特殊解释。此外,您可能至少想使用查找表或开关
。Escape the slashes (use
" \\a"
) so they won't get interpreted specially. Also you might want to use a lookup table or aswitch
at least.字符串文字中的反斜杠需要转义;您需要
"\\0"
,而不是"\0"
。查找表可能会减轻这个痛苦:
是的,
ecs
中的大多数条目都将为 NULL;权衡是我不必担心将字符值映射到数组索引。Backslashes in string literals need to be escaped; instead of
"\0"
, you need"\\0"
.A lookup table might make this less painful:
Yes, the majority of entries in
ecs
are going to be NULL; the tradeoff is that I don't have to worry about mapping the character value to array index.