C & C++ fundamentals / 03
Reading input with scanf
Read integers, floating-point values, and characters into variables using scanf.
On this page
Now let's learn how to read input. We covered format specifiers in the previous lesson because they are needed for the scanf() examples here.
To read a decimal integer, declare a variable and pass its address after the format string:
#include <stdio.h>
int main()
{
int num;
scanf("%d",&num);
return 0;
}
Here, %d describes the input format, and the value is stored in num. The ampersand in &num is important: it gives scanf the address at which to store the result. Omitting it in these examples is incorrect and can make the program fail.
Match the variable to the input format
You must declare a variable to hold the input. There are several variable types; these three are enough for the first examples:
int: an integer.float: a floating-point number.char: a character.
There are other types, which we will introduce as they become necessary. For now, match each type to the appropriate format specifier.
Decimal integer
// Decimal integer
#include <stdio.h>
int main()
{
int num;
scanf("%d",&num);
return 0;
}
Floating-point number
// Floating-point number
#include <stdio.h>
int main()
{
float num;
scanf("%f",&num);
return 0;
}
Character
// Character
#include <stdio.h>
int main()
{
char ch;
scanf("%c",&ch);
return 0;
}
Editorial note: these are minimal teaching examples. Real programs should check
scanf's return value before using the result. The address-of rule above applies to the scalar variables shown; an array used with%sis a different case.
Moved here from Tistory
I migrated this post from my Korean Tistory blog, I am Jason Lee, to this website and translated it into English. My writing and projects now live together in one place.
The original publication date, code examples, and screenshots are preserved. Editorial notes clarify known issues in the original material.
Original post on Tistory English edition · Aug 30, 2026