← Back to C Course | Chapter 2: Input & Output | Lesson 3 of 7

C scanf()

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()?

c
#include <stdio.h>
int main() {
	int age;
	sscanf("25", "%d", &age);
	printf("%d", age);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int age;
	sscanf("25", "%d", &age);
	printf("%d", age);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	char grade;
	sscanf("A", "%c", &grade);
	printf("%c", grade);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	float price;
	sscanf("19.99", "%f", &price);
	printf("%.2f", price);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int count;
	float price;
	sscanf("3 9.99", "%d %f", &count, &price);
	printf("%d %.2f", count, price);
	return 0;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.