Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't getchar() read characters such as backspace?

Tags:

c

getchar

This is a very basic C question, coming from page 18 of Kernighan and Ritchie.

I've compiled this very simple code for counting characters input from the keyboard:

#include <stdio.h>

/* count characters in input; 1st version */
main()
{
  long nc;

  nc = 0;
  while (getchar() != EOF)
    ++nc;
  printf("%1d\n", nc);
}

This compiles fine, runs fine, and behaves pretty much as expected i.e. if I enter "Hello World", it returns a value of 11 when I press CTRLD to give the EOF character.

What is confusing me is if I make a mistake, I can use backspace to delete the characters and re-enter them, and it returns only the number of characters displayed by the terminal when I invoke EOF.

If the code is counting each character, including special characters, if I type four characters, delete two, and type another two, shouldn't that output as 8 characters (4 char + 2 del + 2 char), not 4?

I'm obviously misunderstanding how C handles backspace, and how/when the code is incrementing the variable nc?

like image 705
Philip King Avatar asked Feb 14 '17 10:02

Philip King


Video Answer


2 Answers

Typically, your terminal session is running in "line mode", that is, it only passes data to your program when a line is complete (eg, you pressed Return, etc). So you only see the line as it is complete (with any editing having been done before your program ever sees anything). Typically this is a good thing, so every program doesn't need to deal with delete/etc.

On most systems (eg Unix-based systems, etc), it is possible to put the terminal into "raw" mode -- that is, each character is passed as received to the program. For example, screen-oriented text editors commonly do this.

like image 100
John Hascall Avatar answered Sep 19 '22 17:09

John Hascall


It's not that getchar() doesn't count the "deletions" but it doesn't even see the input until it's passed to your program by the terminal driver.

When you input something, it doesn't reach your C program until you press \n or send EOF (or EOL). This is what POSIX defines as Canonical Mode Input Processing - which is typically the default mode.

like image 28
P.P Avatar answered Sep 17 '22 17:09

P.P