String input using getchar()

user191776 picture user191776 · Sep 7, 2010 · Viewed 16.9k times · Source

The following code uses getchar() to accept a line of input.

#include <stdio.h>
#include <stdlib.h>

int main()
{
 char *rawString = (char *)malloc(200*sizeof(char));
 char *rawStringInitial = rawString;
 char c;
 c=getchar();
 while(c!='\n')
 {
  *rawString=c;
  rawString++;
  c=getchar();
 }
 *rawString='\0';
 printf("\n[%s]\n",rawStringInitial);
 return(0);
}

While typing, if I press backspace, shouldn't it also be received by getchar() & stored in the rawString-pointed location? However the output simply shows the final string without any special characters. Could someone explain why?

Answer

John Bode picture John Bode · Sep 7, 2010

Standard input is (usually) buffered; non-printing characters like backspace are handled by the terminal server, and library functions like getchar() will never see them.

If you need to read raw keystrokes, then you will need to use something outside of the C standard library.