scanf
Function
Finally, this is why we really needed pointers! 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!
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
.
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!