C Program to demonstrate the ‘getchar’ function.

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 from stdin and returns it as an int.
  • It returns int — not char — so it can also return the special value EOF (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 to ch, all inside the while condition.
  • The loop keeps going as long as the character is not a newline ('\n') and not EOF, incrementing count each time.
  • When the user presses Enter, getchar() returns '\n', the loop stops, and the total is printed.
  • ch is declared int (not char) so the comparison with EOF is reliable — a very common beginner bug is declaring it char.

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>