为什么这个 C 程序不会拾取转义的反斜杠?

发布于 2024-09-14 00:08:09 字数 856 浏览 1 评论 0原文

我正在做 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

只为一人 2024-09-21 00:08:09

您可能需要 printf("\\\\");,而不仅仅是 printf("\\\\");

You probably want to printf("\\\\");, instead of just printf("\\");.

ヤ经典坏疍 2024-09-21 00:08:09

您应该打印反斜杠及其转义符

目前,您只是打印反斜杠 - 在这里您要转义第二个反斜杠,否则它会转义结束双引号:

printf("\\");

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("\\");
灼痛 2024-09-21 00:08:09

使用 printf("\\\\")

Use printf("\\\\")

ぇ气 2024-09-21 00:08:09

当 C 编译器在源代码中找到 \\ 时,它会做什么?

What does the C compiler do when it finds \\ in the source?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文