C User Input
Most real programs need data from the person using them. In C, keyboard input is read from the standard input stream, stdin, using functions from <stdio.h>. The two you will use most are scanf, which reads formatted values like numbers, and fgets, which reads a whole line of text.
Note: The playgrounds on this site cannot type into a running program, so the examples that read the keyboard are shown as normal code blocks with a sample session. To still let you experiment, the runnable examples use
sscanf, which parses text from a string in exactly the same wayscanfparses the keyboard.
Reading a number with scanf
scanf uses format specifiers like printf, but it needs to know where to store each value. You pass the variable's address with the & operator:
#include <stdio.h>
int main(void) {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("Next year you will be %d.\n", age + 1);
return 0;
}Enter your age: 29
Next year you will be 30.Forgetting the & is a classic bug: scanf then receives the (garbage) value of age and treats it as an address, which usually crashes the program.
Specifiers for scanf
| Type | scanf specifier |
Note |
|---|---|---|
int |
%d |
|
float |
%f |
|
double |
%lf |
different from printf, where %f works for both |
char |
%c / %c |
a leading space skips whitespace such as a left-over newline |
string (char[]) |
%s / %19s |
reads one word; no & because an array is already an address; always give a width |
Reading several values
scanf can read multiple values in one call. It skips whitespace (spaces, tabs, newlines) between numbers. Here sscanf parses a fixed string so you can run it:
#include <stdio.h>
int main(void) {
const char *typed = "12 7.5 kg"; // pretend the user typed this
int count;
double weight;
char unit[8];
int matched = sscanf(typed, "%d %lf %7s", &count, &weight, unit);
printf("matched %d values\n", matched);
printf("%d boxes of %.1f %s = %.1f %s\n", count, weight, unit, count * weight, unit);
return 0;
}matched 3 values
12 boxes of 7.5 kg = 90.0 kg
Always check the return value
scanf (and sscanf) return how many values were successfully read. If the user types letters where a number is expected, that count is lower than you asked for and the variables are left untouched. Checking it is the first step towards robust input:
#include <stdio.h>
int main(void) {
const char *inputs[] = {"42", "abc", "3.9", ""};
for (int i = 0; i < 4; i++) {
int value = -1;
int ok = sscanf(inputs[i], "%d", &value);
if (ok == 1) {
printf("\"%s\" -> read %d\n", inputs[i], value);
} else {
printf("\"%s\" -> not a number (returned %d)\n", inputs[i], ok);
}
}
return 0;
}"42" -> read 42
"abc" -> not a number (returned 0)
"3.9" -> read 3
"" -> not a number (returned -1)
Notice that "3.9" is read as 3: %d stops at the first character that cannot belong to an integer. An empty input returns EOF (-1).
Reading a line of text with fgets
scanf("%s", ...) stops at the first space, so it cannot read a full name like "Ada Lovelace". fgets reads a whole line, including spaces, and never writes more than the buffer size:
#include <stdio.h>
#include <string.h>
int main(void) {
char name[50];
printf("Full name: ");
if (fgets(name, sizeof name, stdin) != NULL) {
name[strcspn(name, "\n")] = '\0'; // remove the trailing newline
printf("Hello, %s!\n", name);
}
return 0;
}Full name: Ada Lovelace
Hello, Ada Lovelace!fgets keeps the newline the user typed (if it fits). The line name[strcspn(name, "\n")] = '\0'; finds it and cuts it off.
The robust pattern: fgets + sscanf
Mixing scanf and fgets causes trouble, because scanf leaves the newline in the input buffer and the next fgets reads an empty line. A cleaner approach is to always read a full line with fgets, then parse it with sscanf. Here is that idea with lines simulated by an array:
#include <stdio.h>
#include <string.h>
int main(void) {
// Each string stands for one line the user typed (fgets keeps the '\n')
char lines[3][32] = {"Lin Wei\n", "notanumber\n", "34\n"};
char name[32];
strcpy(name, lines[0]);
name[strcspn(name, "\n")] = '\0';
int age;
int line = 1;
while (sscanf(lines[line], "%d", &age) != 1) {
printf("'%.*s' is not a valid age, asking again...\n",
(int) strcspn(lines[line], "\n"), lines[line]);
line++;
}
printf("%s is %d years old.\n", name, age);
return 0;
}'notanumber' is not a valid age, asking again...
Lin Wei is 34 years old.
In a real program, each lines[...] would come from fgets(buffer, sizeof buffer, stdin).
Summary
| Task | Use |
|---|---|
| Read numbers quickly | scanf("%d", &n) and check the return value |
| Read a full line of text | fgets(buf, sizeof buf, stdin) |
| Robust input | fgets a line, then sscanf it |
| Read one word safely | scanf("%19s", word) with a width one less than the buffer |
Warning: Never use
gets— it has no size limit and was removed from the language in C11. Never use%swithout a width inscanf.
Test yourself
Why do you write &age in scanf("%d", &age);?
- To print the age
- scanf needs the address of the variable to store the value there
- It converts age to a string
- It is optional decoration
Which specifier reads a double with scanf?
- %f
- %d
- %lf
- %g
What does scanf return?
- The value it read
- The number of values successfully read
- Always 0
- The number of characters typed