C
Reading Keyboard Input in C Without Getting Stuck: scanf, Its Return Value, and fgets
Introduction
Reading a number from the keyboard is one of the first things every C course teaches, usually with a single line: scanf("%d", &n);. It works perfectly as long as the person at the keyboard types exactly what the programmer expected. The moment they type a word, a decimal, or a number followed by something else, the program can freeze in an endless loop, silently use a wrong value, or charge someone a negative price.
In this tutorial we will build a small console for a bike-rental kiosk and make it survive real people. We will start with the one-line scanf version and watch it lock up. Then we will look at what scanf actually returns, where the characters it rejects go, and why reading a whole line with fgets and checking it afterwards is the approach that holds up. We will finish by feeding the kiosk a file instead of the keyboard.
I will assume you are working in the C/C++ sandbox on Bytestark, in /home/coder/learning, and that you have compiled a C program with gcc before. Every run in this tutorial is interactive: you type the values shown after each prompt and press Enter.
Background
When you type in the terminal, your characters do not go straight to the program. They are collected into a line, and only when you press Enter is the whole line, including the newline character at its end, handed to the program. The program receives it through standard input, usually called stdin: a stream of characters that the program reads from the front. Characters that the program has not read yet stay in the stream, in order, waiting for the next read.
scanf reads characters from stdin and converts them according to a format string, the same kind of string printf uses. %d means "skip any spaces, then read an integer written in decimal". To store the result, scanf needs to know where the variable lives in memory, which is why you write &hours and not hours: the & operator gives the address of a variable, the place in memory where it is stored.
Three more terms come up in this tutorial:
- EOF, end of file, is what a read reports when the stream has nothing more to give. In a terminal you produce it by pressing Ctrl+D at the start of a line. When input comes from a file, it happens at the end of the file.
getchar()reads one single character fromstdinand returns it, or returns the special valueEOFwhen there is nothing left.fgetsreads one whole line, up to and including the newline, into an array of characters, which C calls a string buffer.
Practical Scenario
A bike-rental shop by the river has a kiosk at the door. Staff type in how many hours each customer wants, the kiosk shows the charge at 4 EUR per hour, and at closing time they type 0 to see the day's total. Rentals go from 1 to 8 hours. The kiosk runs a small C program on a single-board computer, and it is the only way the shop takes payments.
On a busy Saturday the staff are fast and not careful. A customer says "two hours" and the word two gets typed. Someone types 2.5 for a two-and-a-half-hour ride. Someone types 3 bikes. If any of that freezes the kiosk, the queue stops and the shop has to restart a machine with a line of tourists watching. If it is accepted with the wrong value, the shop loses money without anyone noticing.
The program has to do three things the naive version does not: refuse anything that is not exactly a whole number, keep working after it refuses, and never charge for a rental the shop does not offer.
The Problem
Here is the kiosk as it was first written. It asks for the hours, prices the rental, adds it to the day's total, and stops when it reads 0.
Create the file:
touch rental.c
Put this in it:
#include <stdio.h>
int main(void) {
int hours = 0;
int total = 0;
while (1) {
printf("Hours for this rental (0 to finish): ");
scanf("%d", &hours);
if (hours == 0) {
break;
}
int price = hours * 4;
printf("Charge: %d EUR\n", price);
total += price;
}
printf("Day total: %d EUR\n", total);
return 0;
}
Build it and run it. Type 3, then 2, then 0:
gcc -Wall -Wextra -o rental rental.c && ./rental
Hours for this rental (0 to finish): 3
Charge: 12 EUR
Hours for this rental (0 to finish): 2
Charge: 8 EUR
Hours for this rental (0 to finish): 0
Day total: 20 EUR
With careful input the kiosk works. while (1) is a loop whose condition is always true, so it repeats until something inside it says break, which here is reading 0. Each pass prints a prompt, reads an integer into hours, and either stops or prints the charge. total += price; is short for total = total + price;, adding this rental to the running total.
Now run it again and type 3, then two:
./rental
Hours for this rental (0 to finish): 3
Charge: 12 EUR
Hours for this rental (0 to finish): two
Charge: 12 EUR
Hours for this rental (0 to finish): Charge: 12 EUR
Hours for this rental (0 to finish): Charge: 12 EUR
Hours for this rental (0 to finish): Charge: 12 EUR
Hours for this rental (0 to finish): Charge: 12 EUR
The screen fills with prompts and charges as fast as the terminal can print them, and the program never waits for you again. Press Ctrl+C to stop it. Two things are wrong at once. The kiosk charged 12 EUR for two, which is the charge of the previous rental. And it never asked again, it just kept going. Before we can fix it, we need to know what scanf did with the word two.
What scanf Returns, and What It Leaves Behind
scanf does more than store a value: it also returns a number, and the naive kiosk ignored it. Let's write a tiny separate program that shows us that return value and the next character still waiting in stdin.
Create the file:
touch probe.c
Put this in it:
#include <stdio.h>
int main(void) {
int hours = -1;
printf("Hours: ");
int matched = scanf("%d", &hours);
printf("scanf returned %d, hours is %d\n", matched, hours);
int next = getchar();
if (next == '\n') {
printf("next character waiting: newline\n");
} else if (next == EOF) {
printf("next character waiting: none (end of input)\n");
} else {
printf("next character waiting: '%c'\n", next);
}
return 0;
}
hours starts at -1 so we can see whether scanf changed it. The if/else if chain only exists to print the next character in a readable way, since a newline would otherwise just break the output line.
Build it, run it, and type 3:
gcc -Wall -Wextra -o probe probe.c && ./probe
Hours: 3
scanf returned 1, hours is 3
next character waiting: newline
scanf returned 1. Its return value is the number of placeholders it successfully filled, and our format has one, %d. It read the 3, stopped at the first character that cannot be part of a number, and that character, the newline from pressing Enter, is still in the stream.
Run it again and type two:
./probe
Hours: two
scanf returned 0, hours is -1
next character waiting: 't'
This explains the frozen kiosk. scanf returned 0: it filled no placeholders, because t cannot start a number. It did not touch hours, which is still -1. And it did not consume anything: the t is still the next character, with wo and the newline behind it. In the kiosk, the loop then asked again, scanf looked at the same t, failed again without consuming it, and so on forever. Because hours was never changed, it still held 3 from the previous rental, so every pass printed Charge: 12 EUR.
Two more inputs complete the picture. Run it and type 2.5:
./probe
Hours: 2.5
scanf returned 1, hours is 2
next character waiting: '.'
This one is quieter and worse. scanf happily read 2, reported success, and left .5 in the stream. A two-and-a-half-hour rental would be charged as two.
Finally, run it and press Ctrl+D instead of typing anything:
./probe
Hours: scanf returned -1, hours is -1
next character waiting: none (end of input)
At end of input, scanf returns the special value EOF, which is -1. So there are three kinds of result: the number of values filled (1 here), 0 for "there was input but it did not match", and EOF for "there is no more input at all". A program that does not look at the return value cannot tell them apart.
Try it: Run ./probe and type 12abc. Before you press Enter, predict the return value, the value of hours and the next character. You will see scanf returned 1, hours is 12 and next character waiting: 'a': %d takes as many digits as it can and stops at the first non-digit, without complaining about what follows.
Checking the Return Value and Clearing the Bad Line
The first fix follows directly from what we saw. The kiosk must check what scanf returned, and when it is 0, it must throw away the rejected characters, or the next scanf will trip over them again.
Replace the whole of rental.c with:
#include <stdio.h>
int main(void) {
int hours = 0;
int total = 0;
while (1) {
printf("Hours for this rental (0 to finish): ");
int matched = scanf("%d", &hours);
if (matched == EOF) {
break;
}
if (matched != 1) {
printf("Please type a whole number of hours.\n");
int c;
while ((c = getchar()) != '\n' && c != EOF) {
}
continue;
}
if (hours == 0) {
break;
}
int price = hours * 4;
printf("Charge: %d EUR\n", price);
total += price;
}
printf("Day total: %d EUR\n", total);
return 0;
}
Build it, run it, and type 3, two, 2, 0:
gcc -Wall -Wextra -o rental rental.c && ./rental
Hours for this rental (0 to finish): 3
Charge: 12 EUR
Hours for this rental (0 to finish): two
Please type a whole number of hours.
Hours for this rental (0 to finish): 2
Charge: 8 EUR
Hours for this rental (0 to finish): 0
Day total: 20 EUR
two is refused with a message, the kiosk asks again, and the total is 20 EUR: the 12 and 8 for the two real rentals, nothing for the refused line. Here are the new pieces.
int matched = scanf("%d", &hours);keeps the return value instead of throwing it away.if (matched == EOF) { break; }handles the end of input. Without it, pressing Ctrl+D would make every laterscanfreturnEOFimmediately, and we would have a new endless loop.if (matched != 1)catches the "input did not match" case. It prints a message and then empties the rest of the line.while ((c = getchar()) != '\n' && c != EOF) { }is the line that does the emptying, and it packs a lot into one condition. Read it from the inside out.c = getchar()reads one character and stores it inc. The parentheses around it make that assignment happen first, and its value is the character just read. That character is then compared with'\n': if it is not a newline, and also notEOF, the condition is true and the loop runs again with an empty body. So the loop reads and discardst,w,o, and stops after it has read the newline. Thec != EOFpart stops it if the input ends in the middle of a line, which would otherwise loop forever becausegetcharkeeps returningEOF.int cis anint, not achar, becausegetcharreturns either a character orEOF, andEOFis a value that does not fit among the characters. Storing it in acharcan make thec != EOFtest fail.continue;skips the rest of this pass and jumps straight to the next one, which prints the prompt again.
This version no longer freezes. But it still trusts scanf too much. Run it and type 2.5, then 0:
./rental
Hours for this rental (0 to finish): 2.5
Charge: 8 EUR
Hours for this rental (0 to finish): Please type a whole number of hours.
Hours for this rental (0 to finish): 0
Day total: 8 EUR
2.5 was accepted as 2 and charged 8 EUR. Then, without waiting for any typing, the next prompt immediately complained, because the leftover .5 was waiting in the stream and %d cannot read a number starting with .. The staff member sees an error message for something they never typed. The same happens with 3 bikes: 3 is accepted, and bikes causes a puzzling error on the next prompt.
The root of the problem is that scanf reads only as much of the line as it needs, so one typed line can be split across two prompts.
Try it: Delete the three lines that declare c and run the while (getchar...) loop, keep the message and the continue, rebuild and type two. Predict what happens. The kiosk prints Please type a whole number of hours. over and over without waiting, which is the original endless loop with a different message: refusing the input is not enough if the rejected characters stay in the stream. Put the lines back.
Reading a Whole Line With fgets
The fix is to stop letting the conversion decide how much to read. We read the entire line the person typed, newline included, and then examine that line on its own. Whatever happens, the next prompt starts with a fresh line.
fgets does the reading, and sscanf does the examining. sscanf works exactly like scanf, except that it reads from a string you give it instead of from stdin. Replace the whole of rental.c with:
#include <stdio.h>
int main(void) {
char line[32];
int hours = 0;
int total = 0;
while (1) {
printf("Hours for this rental (0 to finish): ");
if (fgets(line, sizeof line, stdin) == NULL) {
break;
}
char extra;
if (sscanf(line, "%d %c", &hours, &extra) != 1) {
printf("Please type a whole number of hours.\n");
continue;
}
if (hours == 0) {
break;
}
int price = hours * 4;
printf("Charge: %d EUR\n", price);
total += price;
}
printf("Day total: %d EUR\n", total);
return 0;
}
Build it, run it, and type 3, 2.5, 3 bikes, two, an empty line (just press Enter), 2 and 0:
gcc -Wall -Wextra -o rental rental.c && ./rental
Hours for this rental (0 to finish): 3
Charge: 12 EUR
Hours for this rental (0 to finish): 2.5
Please type a whole number of hours.
Hours for this rental (0 to finish): 3 bikes
Please type a whole number of hours.
Hours for this rental (0 to finish): two
Please type a whole number of hours.
Hours for this rental (0 to finish):
Please type a whole number of hours.
Hours for this rental (0 to finish): 2
Charge: 8 EUR
Hours for this rental (0 to finish): 0
Day total: 20 EUR
Every bad line is refused exactly once, at the prompt where it was typed, and only 3 and 2 are charged. Let's go through it.
char line[32]; is the buffer: an array of 32 characters that will hold one line of input. Thirty-two is far more than anyone needs to type a number of hours.
fgets(line, sizeof line, stdin) reads from stdin into line. The middle argument is the size of the buffer, and fgets never writes more than that: it reads at most 31 characters and always adds a terminating zero byte, which is how C marks the end of a string. It stops after the newline, and keeps the newline in the buffer. When you type 2.5 and Enter, line holds the characters 2, ., 5, \n and the zero byte. Passing sizeof line rather than a typed 32 means the two numbers can never disagree, the same idea as computing an array's length with sizeof.
fgets returns NULL, a special "no address" value, when there is nothing left to read. That is our end-of-input check, and it replaces the EOF test from the previous version.
sscanf(line, "%d %c", &hours, &extra) is where the checking happens, and the format string is the clever part. %d reads the integer. The space after it means "skip any whitespace", which includes the newline at the end of the line. Then %c tries to read one more character into extra. Look at what that does for each input:
- For
3,%dreads 3, the space skips the newline, and%cfinds nothing left. One placeholder was filled, sosscanfreturns 1, and the line is accepted. - For
2.5,%dreads 2, and%creads the.. Two placeholders were filled,sscanfreturns 2, and the line is refused. - For
3 bikes,%dreads 3, the space skips the space, and%creadsb. That is 2 again, refused. - For
two,%dfails at once,sscanfreturns 0, refused. - For the empty line, there is nothing but a newline, so
sscanfreaches the end of the string before filling anything and returnsEOF. That is not 1, so it is refused too.
So "returns exactly 1" means "the line holds one integer and nothing else but whitespace", which is precisely the rule the kiosk needs. We never use the value in extra; it exists only so that sscanf has somewhere to put an unwanted character and can tell us it found one.
Notice what disappeared: the getchar loop. Because fgets always consumes the whole line, there is never anything left over to clear.
Note: If someone types more than 31 characters, fgets returns the first 31 and leaves the rest for the next call, so a very long line would still be split. For a field that holds a number of hours this cannot happen in practice. Programs that read longer text check whether the buffer ends with \n and discard the rest of the line if it does not.
Try it: Change the format to "%d" and the call to sscanf(line, "%d", &hours), rebuild, and type 2.5, 3 bikes, 0. Predict the charges. gcc warns unused variable ‘extra’, and the kiosk charges 8 EUR and 12 EUR, because without the trailing %c nothing looks past the number. At least the leftovers no longer cause an error at the next prompt, since the whole line was consumed. Put the " %c" and &extra back.
Refusing Rentals the Shop Does Not Offer
The kiosk now only accepts whole numbers. But a whole number is not necessarily a sensible one. Run it, type -3, 12 and 0:
./rental
Hours for this rental (0 to finish): -3
Charge: -12 EUR
Hours for this rental (0 to finish): 12
Charge: 48 EUR
Hours for this rental (0 to finish): 0
Day total: 36 EUR
A negative charge is a refund the shop never agreed to, and it was subtracted from the day's total, which is now 36 EUR instead of 48. A 12-hour rental is longer than the shop is open. Checking that the input is a number is not the same as checking that it is valid.
Add this check right after the if (hours == 0) block, before the price is calculated:
if (hours < 0 || hours > 8) {
printf("Rentals are 1 to 8 hours.\n");
continue;
}
Rebuild, run, and type 3, -3, 12, 8, 0:
gcc -Wall -Wextra -o rental rental.c && ./rental
Hours for this rental (0 to finish): 3
Charge: 12 EUR
Hours for this rental (0 to finish): -3
Rentals are 1 to 8 hours.
Hours for this rental (0 to finish): 12
Rentals are 1 to 8 hours.
Hours for this rental (0 to finish): 8
Charge: 32 EUR
Hours for this rental (0 to finish): 0
Day total: 44 EUR
-3 and 12 are refused and do not touch the total. 8 is accepted because the condition is hours > 8, not >=, and the shop does rent for 8 hours. The total is 12 + 32 = 44 EUR.
The order of the checks matters, and it now reads like a sentence: first, is there any input at all (fgets); then, is it a whole number (sscanf); then, is it the "finish" signal (hours == 0); and only then, is it a valid rental (1 to 8). Each check can rely on the ones before it. For example, the range check can compare hours safely because, if sscanf had failed, we would already have gone back to the prompt.
Try it: Move the range check above the if (hours == 0) block and change its condition to hours < 1 || hours > 8, which looks like the same rule. Rebuild, type 3 and then 0, and predict how the day ends. It never does: 0 is now refused as Rentals are 1 to 8 hours. before the finish check sees it, and the only way out is Ctrl+D, which prints the total. Put the checks back in their original order.
Feeding the Kiosk From a File
At closing time on the day the kiosk broke, staff wrote the rentals on paper. Someone typed them into a text file, one per line, and now we want the kiosk to total them. Because our program reads from stdin, and stdin does not have to be the keyboard, we do not need to change a single line of C.
Create the file:
touch shift.txt
Put the paper log in it, including the mistake someone made on the third line:
3
2
three
5
1
Run the kiosk with its input taken from the file:
./rental < shift.txt
Hours for this rental (0 to finish): Charge: 12 EUR
Hours for this rental (0 to finish): Charge: 8 EUR
Hours for this rental (0 to finish): Please type a whole number of hours.
Hours for this rental (0 to finish): Charge: 20 EUR
Hours for this rental (0 to finish): Charge: 4 EUR
Hours for this rental (0 to finish): Day total: 44 EUR
< shift.txt is a shell feature called input redirection. Before starting ./rental, the shell opens shift.txt and connects it to the program's stdin instead of the keyboard. The program cannot tell the difference: fgets still returns one line at a time.
The output looks different from the interactive runs for one reason only. When you type, the terminal echoes your characters, so the number appears after the prompt. When input comes from a file, nothing is echoed, so each prompt is followed directly by the program's reply. The values are the same: 3, 2 and 5 hours give 12, 8 and 20 EUR, 1 hour gives 4 EUR, and three is refused.
There is no 0 at the end of the file, and the program still finished cleanly. After the last line, fgets returned NULL, our end-of-input check ran break, and the total was printed. This is the reason we handled end of input explicitly: a file always ends, and a program that only stops on a typed 0 would never stop on one that does not contain it.
Try it: Add a line -2 to the end of shift.txt and run ./rental < shift.txt again. Predict the last two lines of output. The line -2 produces Rentals are 1 to 8 hours., and the total stays at Day total: 44 EUR, because the same validation applies whether the input is typed or read from a file.
Summary
We turned a kiosk program that froze on the first unexpected word into one that refuses bad input once, keeps working, rejects rentals the shop does not offer, and reads a file as happily as the keyboard. We deliberately stopped at whole numbers within the range of int. Detecting numbers too large for an int, which sscanf does not report, is the job of strtol, and it belongs in a follow-up.
scanfreturns the number of placeholders it filled, 0 when the input does not match, andEOFwhen there is no more input. Ignoring that value means you cannot tell a valid read from a failed one.- When a conversion fails,
scanfleaves the offending characters instdin, so the nextscanffails on the same characters and a loop around it never ends. %dstops at the first character that cannot belong to a number and reports success, so2.5and3 bikesare read as 2 and 3 with the rest left behind.- Read whole lines with
fgets(buffer, sizeof buffer, stdin)and check them withsscanf, so each prompt always consumes exactly one typed line and nothing leaks into the next. - The format
"%d %c"with a required return value of 1 accepts a line that holds one integer and nothing else but whitespace. - Store
getchar's result in anint, and stop any reading loop onEOFas well as on the value you are looking for. - Checking that input is a number is not the same as checking that it is valid; test the allowed range separately, after the format check and after any special values such as
0for "finish". - A program that reads
stdincan take its input from a file with./program < file; it then reaches end of input when the file ends, so it must handleEOFcleanly.