Course contentsShow
← C
Lesson 682 of 1,21910. Input and OutputFree lesson

Using while loops with getchar

Using while loops with getchar

What you'll learn: How to process a sequence of characters one by one until the user finishes their input.

The character assembly line

Think of getchar() as a small mechanical arm that grabs exactly one character from your keyboard's "conveyor belt" (the input buffer). By itself, it’s not very powerful. But when you put that arm inside a while loop, you create a processing station that can handle entire sentences, paragraphs, or books, one single character at a time.

This pattern is the backbone of text processing in C. Instead of trying to guess how long a user's message will be, you simply tell the computer: "Keep grabbing a character as long as there are characters to grab."

The "End of File" signal

To make a loop work, we need a stopping condition. In C, we use a special constant called EOF (End Of File). When you press a specific key combination (Ctrl+D on Linux/Mac or Ctrl+Z on Windows), the system sends an EOF signal. This tells getchar() that the conveyor belt is empty and it’s time to stop.

Putting it into code

Here is the classic way to write this loop. We store each character in a variable, check if it’s EOF, and if not, we do something with it.

#include <stdio.h>

int main() {
    int ch; // Use int, not char, to handle the EOF signal properly

    printf("Type something and press Enter (Ctrl+D/Ctrl+Z to stop):\n");

    // Grab a character, store it in 'ch', and check if it's the end
    while ((ch = getchar()) != EOF) {
        // Example: Print the character back out
        putchar(ch);
    }

    printf("\nFinished reading input.\n");
    return 0;
}

Why this works

Notice the line (ch = getchar()) != EOF. This looks busy, but it’s doing two things at once. First, it assigns the result of getchar() to our variable ch. Second, it checks if that value is the "stop" signal.

Using this method is incredibly memory-efficient. Because the program only holds one character at a time, you could process a file that is gigabytes in size without ever running out of RAM. You are simply checking the "assembly line" piece by piece until the work is done.

Key takeaway

A while loop paired with getchar() != EOF allows you to process input of any length character-by-character until the user signals they are finished.