Xited
Xited

Reputation: 69

How backspace can actually delete the string in getchar() loop

#include <stdio.h>
#include <conio.h>
#define ENTER_KEY '\n'
#define NULL_TERMINATOR '\0'

int main()
{
    char name[100], input;
    int counter = 0;
    while(input != ENTER_KEY)
    {
        input = getchar();
        name[counter] = input;
        counter++;
    }
    counter--;
    name[counter] = NULL_TERMINATOR;
    printf("%s", name);
    return 0;
}

If I write something, it should continuously saved in the name Array. And the counter should go up on every character I enter. But if I press Backspace, it looks like it makes the counter decreased. Because for example if I write "abcdef" and press backspace 3 times and change that to "abcxyz", and then press Enter. It prints "abcxyz".

Upvotes: 2

Views: 160

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148940

It depends on the console driver. On most systems (at least Unix-like in line mode and in Windows console), the program does not receive the characters at the moment they are typed but the system prepares a line (up to the newline character) and sends the full line to the program.

In that case, the backspace if often used to edit that console buffer, meaning that the characters erased are actually removed before being handed to the program. So if you type abcdef<backspace><backspace><backspace>xyz<Return> the program will receive the following string: "abcxyz\n".

Beware, in a GUI program or in fullscreen text mode program like emacs or vi, the system is in raw mode (Unix language) and each character is received when it is typed. In that case, the program has to manage the input and erase its own character array when it receives a <backspace>.

Upvotes: 6

Related Questions