The getchar() function reads a single character from standard input (the keyboard) and returns it. It is one of the simplest input functions in C and a great way to understand how the input buffer works. In this program we use getchar() in a loop to read text entered by the user and count how many characters were typed before the Enter key.
About getchar()
getchar()reads one character at a time fromstdinand returns it as anint.- It returns
int— notchar— so it can also return the special valueEOF(end of file) when there is no more input. - Input is line-buffered: characters are delivered to your program only after the user presses Enter.
The Program
#include <stdio.h>
int main(void)
{
int count = 0;
int ch;
printf("Please enter some text and press Enter:\n");
/* Read characters until Enter (newline) or end-of-input. */
while ((ch = getchar()) != '\n' && ch != EOF)
count++;
printf("You entered %d characters.\n", count);
return 0;
}
How the Program Works
- The expression
(ch = getchar())reads one character and assigns it toch, all inside thewhilecondition. - The loop keeps going as long as the character is not a newline (
'\n') and notEOF, incrementingcounteach time. - When the user presses Enter,
getchar()returns'\n', the loop stops, and the total is printed. chis declaredint(notchar) so the comparison withEOFis reliable — a very common beginner bug is declaring itchar.
This is a clean, standard-C version of the classic example. The original used main() with no return type and #define RETURN 'n' — note that 'n' is the letter n, whereas the newline character is '\n' (with a backslash).
Sample Output
Please enter some text and press Enter: Hello World You entered 11 characters.
(The 11 characters are H e l l o (space) W o r l d.)
getchar() vs Other Input Functions
| Function | Reads | Typical use |
|---|---|---|
getchar() |
One character | Character-by-character processing |
scanf() |
Formatted input | Numbers and words |
fgets() |
A whole line (safely) | Reading strings without overflow |
For a thorough explanation of getchar(), the input buffer and EOF, The C Programming Language by Kernighan and Ritchie is the definitive reference — find it on Amazon.
This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you.
Related C Programs
- C Program to Mask Password Input with Asterisks
- C Program to Compare Two Strings
- Complete List of C Programs
Want to try it instantly? Paste the code into one of the best online C compilers and run it in your browser, or set up a local toolchain with our complete C development environment guide.