C scanf()
In this page:
What is scanf()?
scanf ("scan formatted") reads input the user types at the keyboard and stores it into your program's variables, making it the standard way a C program becomes interactive instead of just running with hardcoded data.
Example: What is scanf()?
#include <stdio.h>
int main() {
int age;
sscanf("25", "%d", &age);
printf("%d", age);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Reading an Integer
Reading an int requires the %d specifier and an ampersand before the variable name (scanf("%d", &age);), because scanf needs the variable's memory address to write the value into -- passing the variable itself instead of its address is a classic beginner bug.
Example: Reading an Integer
#include <stdio.h>
int main() {
int age;
sscanf("25", "%d", &age);
printf("%d", age);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Reading a Character
Reading a single character with %c is sensitive to leftover whitespace or newline characters sitting in the input buffer from a previous scanf call, which can cause the next read to silently grab a space instead of the character you expect.
Example: Reading a Character
#include <stdio.h>
int main() {
char grade;
sscanf("A", "%c", &grade);
printf("%c", grade);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Reading a Floating-Point Value
%f reads a decimal number into a float variable, letting your program accept things like measurements or prices directly from user input rather than only working with values baked into the source code.
Example: Reading a Floating-Point Value
#include <stdio.h>
int main() {
float price;
sscanf("19.99", "%f", &price);
printf("%.2f", price);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Reading Multiple Values Together
A single scanf call can read several values at once, like scanf("%d %f", &count, &price);, as long as the format string lists each specifier in the same order as the variables and matching addresses that follow.
Example: Reading Multiple Values Together
#include <stdio.h>
int main() {
int count;
float price;
sscanf("3 9.99", "%d %f", &count, &price);
printf("%d %.2f", count, price);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: