Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - getchar

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



getchar

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'.
Bye!

 
 
  Published under free license. Design by Interspire