scanf in C reads formatted input from standard input and stores the converted values through the pointers you pass, for example scanf("%d", &age). It returns the number of items it successfully assigned, and you should check that number every time, because scanf does not report bad input any other way.
#include <stdio.h>
int main(void) {
int age;
if (scanf("%d", &age) == 1) {
printf("Age: %d\n", age);
} else {
printf("That was not a number.\n");
}
return 0;
}
scanf syntax
The function is declared in <stdio.h>. Two sibling functions use the same format language and differ only in where the text comes from:
int scanf(const char *format, ...); // reads stdin
int fscanf(FILE *stream, const char *format, ...); // reads a file stream
int sscanf(const char *buffer, const char *format, ...); // reads a string
After the format string comes one pointer per conversion. The pointer must point at an object of the type that the conversion produces. If it does not, or if the converted value cannot be represented in the object, cppreference states that the behavior is undefined.
Format specifiers you will use most
A conversion specification starts with %, then an optional *, an optional width, an optional length modifier and the conversion letter. These are the common ones:
| Specifier | Target type | What it reads |
|---|---|---|
%d | int * | A signed decimal integer |
%f | float * | A floating-point number |
%lf | double * | A floating-point number stored as a double |
%c | char * | One character, or exactly width characters |
%s | char * | A run of non-whitespace characters, plus a terminating null |
%[set] | char * | A run of characters from the set; %[^\n] means everything up to a newline |
%*d | none | Reads an integer and discards it |
Note the l in %lf. With scanf, %f fills a float and %lf fills a double. (This differs from printf, where %f works for both.)
What scanf returns
The return value is the number of receiving arguments that were successfully assigned. cppreference notes that it may be zero if a matching failure happened before the first assignment. The Linux man page adds that EOF is returned if the end of input is reached before the first successful conversion or a matching failure, and also on a read error.
That gives you three outcomes to tell apart:
- Equal to the number of conversions: everything was read.
- Less than that, but not
EOF: the input did not match. Typingabcfor%dreturns 0. EOF: there was no more input, for example the user pressed Ctrl+D (Linux, macOS) or Ctrl+Z then Enter (Windows console), or a redirected file ran out.
With two conversions, compare against 2, not against "nonzero":
int width, height;
int count = scanf("%d %d", &width, &height);
if (count == EOF) {
puts("No input.");
} else if (count != 2) {
puts("Expected two integers.");
}
If you skip this check, the variables keep whatever value they had, which for an uninitialised local is garbage. This is the most common source of "my program prints a random number" questions.
Why scanf with %s can overflow your buffer
%s stores every non-whitespace character it finds and then a null terminator. It has no idea how big your array is. cppreference warns that %s and %[ may lead to buffer overflow if the width is not provided, and that using them without specifying the destination size is as unsafe as gets.
The fix is a maximum field width. The array needs room for the width plus the terminating null, so the width is one less than the array size:
char name[10];
if (scanf("%9s", name) == 1) {
printf("Hello, %s\n", name);
}
Here at most 9 characters are stored, plus the null, which fills the 10 bytes. The width has to be written into the format string as a literal number. You cannot pass it as an argument the way printf allows with *, because in scanf the * means "discard".
The C11 bounds-checked variant scanf_s takes the size as an extra argument after each %s, %c and %[. cppreference says it is only available if the implementation defines __STDC_LIB_EXT1__ and you define __STDC_WANT_LIB_EXT1__ as 1 before including <stdio.h>. Many compilers do not provide it, so a width in the format string is the portable approach.
The leftover newline problem with %c
Most conversions skip leading whitespace first. cppreference lists the exceptions: %[, %c and %n do not. So after you type a number and press Enter, the newline stays in the input, and a following %c reads that newline instead of waiting for you:
int number;
char letter;
scanf("%d", &number);
scanf("%c", &letter); // reads '\n', not the letter you typed next
Put a space before the conversion. In a format string, any whitespace character consumes all consecutive whitespace in the input, so " %c" skips the newline and then reads one real character:
scanf(" %c", &letter);
The same effect explains why two %d calls in a row work fine whether the numbers are on one line or two: the second %d discards the leftover whitespace itself.
Reading a whole line with spaces
%s stops at the first space, so scanf("%9s", name) given Ada Lovelace stores only Ada and leaves Lovelace in the input for the next call. To read up to the end of the line, use a scanset that excludes the newline, with a width:
char line[64];
if (scanf(" %63[^\n]", line) == 1) {
printf("You typed: %s\n", line);
}
The leading space skips any newline left from earlier input. %63[^\n] then stores up to 63 characters that are not a newline, and adds the null. Anything beyond 63 characters stays unread in the input.
For line-oriented input, many programmers prefer to read the line with fgets and then parse it with sscanf. That way a bad line is consumed completely, and you can report the error and ask again, instead of being stuck with leftover characters that make every later scanf fail.
Reading until the input ends
Because scanf returns the count of assigned items, you can use it as a loop condition. This sums integers from standard input until it ends or hits something that is not a number:
int value;
long total = 0;
while (scanf("%d", &value) == 1) {
total += value;
}
printf("Total: %ld\n", total);
If you need a refresher on loop forms, see For Loop in C: Syntax, Examples, break and continue. Note that this loop stops silently on the first bad token. If you need to tell "end of input" from "bad input", store the return value and compare it with EOF after the loop.
Skipping fields and checking numbers
The assignment-suppression character * parses a field without storing it, which is handy for ignoring a column. cppreference's own example uses %*d for this. Suppressed conversions are not counted in the return value, so a format with one stored field and one skipped field returns at most 1.
int id, score;
// input: "17 alice 92"
int count = sscanf("17 alice 92", "%d %*s %d", &id, &score);
// count is 2: id = 17, score = 92 (example result)
Remember that a value too large for its target type is undefined behavior, not a clean error. Reading 99999999999 with %d into an int gives you no reliable result and no warning from scanf. If the input is untrusted and you need range checks, read the text and convert it with a function whose error reporting you control, such as strtol, rather than relying on %d.
If scanf seems to ignore your input
- It works once, then loops forever. A conversion failed and left the bad text in the input. The next call fails on the same text. Discard the rest of the line (for example
int ch; while ((ch = getchar()) != '\n' && ch != EOF) {}) before retrying. - A
%creads a newline. Use" %c"with the leading space. - Floats come out wrong. Check that you used
%lffor adouble.
Frequently asked questions
- What does scanf return in C?
- scanf returns the number of input items it successfully matched and assigned. That number can be zero, or lower than you asked for, if the input did not match the format. It returns EOF if the input ended or a read error happened before the first conversion or matching failure.
- Why does scanf not need an ampersand for a string?
- An array name decays to a pointer to its first element, and scanf needs a pointer to the place where it should store the value. For int, double and char you pass the address with &. For a char array used with %s, the array name already is that address.
- Why is scanf with %s unsafe?
- Without a width, %s keeps storing characters until it sees whitespace, however long the input is. cppreference says that using %s or %[ without specifying the destination array size is as unsafe as gets. Always give a width one smaller than the array, for example %9s for char name[10].
- What is the difference between scanf, fscanf and sscanf?
- They parse the same format strings from different sources. scanf reads from standard input, fscanf reads from a FILE stream you pass in, and sscanf reads from a string already in memory.