Reading input until EOF with while
What you'll learn: How to use a while loop to process an unknown amount of data until the input stream ends.
The "Bottomless" Inbox
Imagine you are an office clerk with an inbox on your desk. People drop documents in one by one. You don't know if there are three documents coming today or three thousand. You simply have a rule: "As long as there is a paper in the tray, pick it up and process it." Once the tray is empty and the office closes, you stop.
In C programming, we often face this exact scenario. We might want to read characters or numbers from a user or a file, but we don't know ahead of time when they will stop typing or when the file ends. To handle this, we use the while loop combined with a special signal called EOF, which stands for "End Of File."
Using EOF as a Stop Sign
The scanf function does more than just read data; it also returns a value. If it successfully reads an item, it returns the number of items it found. However, if it hits the end of the input (the "bottom" of the tray), it returns EOF.
We can place the scanf call directly inside the while loop's condition. This tells C: "Try to read something. If you succeed, run the code inside the curly braces. If you hit the end of the input, stop the loop."
#include <stdio.h>
int main() {
int number;
printf("Enter numbers (Press Ctrl+D or Ctrl+Z to stop):\n");
// The loop keeps running as long as scanf successfully reads an integer
while (scanf("%d", &number) != EOF) {
printf("You entered: %d\n", number);
}
printf("Input finished. Goodbye!\n");
return 0;
}
How to Test It
When you run a program like this, it will wait for you to type. You can type a number, hit Enter, type another, and hit Enter again. To tell the program you are finished (to "send" the EOF signal manually):
- On Linux or macOS, press
Ctrl + D. - On Windows, press
Ctrl + Zand then hitEnter.
The while loop sees that signal, realizes the "tray" is empty, and gracefully exits.
Key takeaway
Use while (scanf(...) != EOF) to process data continuously until the user or a file signals that there is nothing left to read.