为什么这个 C 程序不会拾取转义的反斜杠?
我正在做 K&R 的练习 1-10
编写一个程序,将其输入复制到输出,用
\t
替换每个制表符,用\b
替换每个退格键,用\\< /代码>。这使得制表符和退格键以明确的方式可见。
我想出了这个......
#include <stdio.h>
int main () {
int c;
printf("\n"); // For readability
while ((c = getchar()) != EOF) {
switch (c) {
case '\t':
printf("\\t");
break;
case '\b':
printf("\\b");
case '\\':
printf("\\");
break;
default:
printf("%c", c);
break;
}
}
}
出于某种原因,它拒绝接触反斜杠。例如,当输入诸如 Hello how\ are you?
之类的字符串时,程序的输出是 Hello\thow\ are you?
这意味着它已将选项卡转换为 OK,但不是反斜杠。
我做错了什么吗?
I'm doing K&R's Exercise 1-10
Write a program to copy its input to its output, replacing each tab by
\t
, each backspace by\b
and each backslash by\\
. This makes tabs and backspaces visible in an unambiguous way.
I came up with this...
#include <stdio.h>
int main () {
int c;
printf("\n"); // For readability
while ((c = getchar()) != EOF) {
switch (c) {
case '\t':
printf("\\t");
break;
case '\b':
printf("\\b");
case '\\':
printf("\\");
break;
default:
printf("%c", c);
break;
}
}
}
For some reason, it refuses to touch backslashes. For example, the output from the program when fed a string such as Hello how\ are you?
is Hello\thow\ are you?
which means it converted the tab OK, but not the backslash.
Am I doing something wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能需要
printf("\\\\");
,而不仅仅是printf("\\\\");
。You probably want to
printf("\\\\");
, instead of justprintf("\\");
.您应该打印反斜杠及其转义符。
目前,您只是打印反斜杠 - 在这里您要转义第二个反斜杠,否则它会转义结束双引号:
You should be printing the backslash and its escape.
Currently you're just printing the backslash - here you're escaping the second backslash which would otherwise escape the closing double quote:
使用 printf("\\\\")
Use
printf("\\\\")
当 C 编译器在源代码中找到
\\
时,它会做什么?What does the C compiler do when it finds
\\
in the source?