Node:getchar, Next:, Previous:Single-character input and output, Up:Single-character input and output


If you want to read a single character from standard input, you can use the getchar function. This function takes no parameters, but reads the next character from stdin as an unsigned char, and returns its value, converted to an integer. Here is a short program that uses getchar:

#include <stdio.h>

int main()
  int input_character;

  printf("Hit any key, then hit RETURN.\n");
  input_character = getchar();
  printf ("The key you hit was '%c'.\n", input_character);
  printf ("Bye!\n");

  return 0;

Note that because stdin is line-buffered, getchar will not return a value until you hit the <RETURN> key. However, getchar still only reads one character from stdin, so if you type hellohellohello at the prompt, the program above will still only get once character. It will print the following line, and then terminate:

The key you hit was 'h'.