如何存储字符'\ b'并使其被c程序文件识别

Har*_*aze 9 c io terminal literals special-characters

当我阅读C语言并进行1-10练习时,有一个问题让我感到困惑.

据说当我输入一个退格键时,该字符由控制台驱动程序处理而不是传递给程序,所以我能做的就是创建一个嵌入了退格的文件.但是,无论我直接输入'\ b,它似乎都没用'或者按Ctrl + H.

当我按下时Ctrl + H,屏幕将显示"\ b",但是当我运行该程序时,程序似乎仍会将其视为两个字符'\'和'b'.无论我输入什么,它在运行程序时都不会显示"\ backspace".

我该怎么做才能使程序将其识别为退格字符?

我的代码如下:

#include <stdio.h>
int main()
{
    int c;
    while((c=getchar())!=EOF){
        if(c=='\t')
            printf("\\t");
        else if(c=='\\')
            printf("\\\\");
        else if(c=='\b')
                 printf("\\backspace");
             else
                 putchar(c);
     }
}
Run Code Online (Sandbox Code Playgroud)

Ruf*_*ind 4

我认为问题不在于您的代码,而在于您在文本编辑器中编写退格字符的方式。

您必须在 vim 中使用特殊的组合键来输入控制字符,例如退格键。在您的情况下,您应该输入ctrl+ v,然后输入ctrl+ h。这应该会产生一个真正的退格字符。

要查看是否生成了实际的退格字符,可以使用hexdump

$ hexdump myfile
00000000  68 65 6c 6c 6f 20 08 77  6f 72 6c 64              |hello .world|
                            ^^
Run Code Online (Sandbox Code Playgroud)

请注意08,它是退格字符(在 C 中,它表示为\b)。


产生退格字符的另一种方法是通过 C 程序简单地编写它:

#include <stdio.h>
int main(void) {
    FILE *f = fopen("myfile", "w");
    fputs("hello \bworld", f);
    fclose(f);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)