scanf Function

Like printf is for printing values, scanf is for reading values from standard input in C.

On the previous pages I talked about pointers, how function parameters are passed by value, and asked you to implement a function which would accept a pointer to an int and read its value from standard input. If you haven't read that, do it now, since it's a prerequisite to understanding how scanf works.

Let's learn how to read values from standard input without carrying around our read_int function. Now you will understand how scanf works.

Not fully, because printf and scanf are also functions which can accept arbitrary number of parameters, but we'll talk about it somewhat later in the course!

So, here is scanf. The following code will read an int value from standard input and assign it to a:

int a;

scanf("%d", &a); /* pass an address! */

Now you should fully understand why we need to pass &a, and not just a, to scanf: we want it to actually change our variable! When scanf sees "%d" in its format string, it reads one number from standard input, and expects to see a pointer to a place in the memory you want to save the value into. Since it's the address of a, the value of variable a will be set.

Reading several variables

scanf is actually much smarter than that. For example, if you want to read three variables–maybe you are reading a date: year, month, and day–you can do it with one scanf call:

int year, month, day;
scanf("%d%d%d", &year, &month, &day);

This usage will assume that there are spaces or linebreaks between values: 2025 4 26. If there's something else, like slashes, you could write it this way:

scanf("%d/%d/%d", &year, &month, &day);

This will accept inputs like 2025/4/26.

There are other format characters, not just %d; we'll talk about them later in the course.

scanf returns number of values read

Sometimes you don't know if your input has finished, or not. It is important to know that scanf returns number of values successfully read. In the above example with the dates, if everything is fine, it will return 3. If not, it might return 0 if no values were read (maybe there was something but not a number), 1 if only one value was there, and so on.

The best way to use scanf is to always compare it with the expected number of parameters you read.

if (scanf("%d/%d/%d", &year, &month, &day) != 3) {
	printf("invalid input!\n");
}

Take some time to play with scanf here, and then I'll give you an exercise on the next page!

#include <stdio.h>

int main() {
	int year, month, day;
	
	if (scanf("%d/%d/%d", &year, &month, &day) != 3) {
		printf("invalid input!\n");
		return 1; /* we return a non-zero exit code if there's an error */	
	}

	printf("we read year: %d, month: %d, day: %d\n", year, month, day);
	return 0;
}

Try entering different inputs, and maybe changing the code, to understand how scanf works. When you are ready, go to the next page!