Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I change backspace to '\b'?

Tags:

c++

c

visual-c++

I see a question in The C Programming Language. It's like this: 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.

Then I write a program like this:

#include<stdio.h>

int main(void)
{
    int c;
    while((c=getchar())!=EOF)
    {
        if(c=='\t')
        {
            putchar('\\');
            putchar('t');
        }
        if(c=='\b')
        {
            putchar('\\');
            putchar('b');
        }
        if(c=='\\')
        {

            putchar('\\');
            putchar('\\');
        }
        else{
            putchar(c);
        }
    }
    return 0;
}

But when I input backspace, I can't get '\b', so how can I get the output '\b'? I.e., I mean, how can I output backspace?

like image 798
zhenganyi Avatar asked Feb 12 '23 14:02

zhenganyi


1 Answers

Keyboard input is preprocessed by the operating system. Most characters are fed directly as input to your program, but some are handled specially.

On UNIX-like systems, standard input is usually line-buffered. The system reads a whole line of text and doesn't pass it on to your program until you press Enter. While reading that line, the system processes Backspace itself; rather than adding a backspace character to the buffer, it erases the most recent character. Your program never sees the '\b' character.

To enter a literal backspace character that can be seen by your program, on a UNIX-like system you can precede it with Ctrl-V. And depending on your tty and terminal emulator settings, typing the Backspace key might transmit an ASCII DEL character rather than backspace. To make sure your program sees a backspace character, type Ctrl-V Ctrl-H.

On non-UNIX-like systems (most likely Windows), there's probably a way to do something similar, but I don't know what it is.

You can also run your program with input from a file. Getting a literal backspace character into the input file is left as an exercise (it depends on the workings of your text editor).

like image 120
Keith Thompson Avatar answered Feb 14 '23 02:02

Keith Thompson