Reading user input: scanf with care
So far your programs only showed fixed data. To make them interactive you need to read what the user types. The classic function is scanf, from <stdio.h>. It looks like printf in its format string, but with a fundamental difference: it must receive the address of the variable where the data is stored, not its value. To get an address you use the & operator. Forgetting that & is one of the most repeated beginner errors.
#include <stdio.h>
int main(void) {
int age;
double height;
printf("Age: ");
if (scanf("%d", &age) != 1) {
printf("Invalid age.\n");
return 1;
}
printf("Height in meters: ");
if (scanf("%lf", &height) != 1) {
printf("Invalid height.\n");
return 1;
}
printf("You are %d years old and %.2f m tall.\n", age, height);
return 0;
}Always check the return value
scanf returns how many items it managed to read and assign. If you expect an integer and the user types hello, it returns 0 and the variable stays untouched, that is, with garbage. That is why the example compares with 1. Ignoring this result is a classic source of failures. Notice also the difference between printf and scanf with real numbers: printf uses %f for double, but scanf requires %lf for double and %f only for float.
The input buffer and the newline
When the user types and presses Enter, the text stays in a buffer, including the newline. scanf with %d reads the number but leaves the newline in the buffer. If you then read a character with %c, you will receive that newline instead of what you expected. One solution is to put a space before the specifier: " %c" skips previous whitespace. Another is to flush the rest of the line with a small loop.
#include <stdio.h>
static void flush_line(void) {
int c;
while ((c = getchar()) != '\n' && c != EOF) {
/* discard characters until end of line */
}
}
int main(void) {
int number;
char answer;
printf("Number: ");
if (scanf("%d", &number) != 1) {
return 1;
}
flush_line();
printf("Continue (y/n)? ");
if (scanf(" %c", &answer) != 1) {
return 1;
}
printf("number=%d answer=%c\n", number, answer);
return 0;
}Reading text: never use gets or unbounded %s
To read a word, scanf("%s", name) copies characters without knowing how many fit in name. If the user types more than was reserved, it overwrites neighboring memory: that is a buffer overflow, the origin of serious vulnerabilities. The function gets was so dangerous that it was removed from the standard in C11. You must always give the maximum: scanf("%19s", name) for an array of 20 characters, because one slot must be left for the null terminator. For whole lines with spaces, the right tool is fgets, which we will see with strings.
#include <stdio.h>
int main(void) {
char name[20];
printf("First name: ");
if (scanf("%19s", name) != 1) { /* at most 19 chars + '\0' */
return 1;
}
printf("Hello, %s!\n", name);
return 0;
}Common mistake: the leftover newline
A mistake that puzzles almost everyone: after scanf("%d", &n), the Enter you pressed stays in the input buffer. If you then call fgets, it reads that leftover newline and returns an empty string, as if the user had typed nothing. The cleanest solution is not to mix the two styles: always read the whole line with fgets and convert it afterwards with sscanf or strtol. That way you control the buffer size, you can try again if the text is not a number and you avoid infinite loops when scanf does not consume invalid input. Always check the value returned by scanf: it is the number of fields read.
#include <stdio.h>
int main(void) {
char line[64];
int age;
printf("Age: ");
if (fgets(line, sizeof line, stdin) == NULL || sscanf(line, "%d", &age) != 1) {
puts("That is not a number.");
return 1;
}
printf("Next year you will be %d.\n", age + 1);
return 0;
}✎ My notes
Saved only in this browser. Sign in to keep it in your account.0/5000 characters