C User Input
Published Aug 26, 2021Updated Mar 27, 2023
Contribute to Docs
The scanf() function, which stands for “scan format”, reads a formatted string from the standard input stream, which is usually the user keyboard.
Syntax
scanf("formatted string", &variable);
Here, the user can enter a value in the terminal, press Enter, and that number will get stored in the pinNumber variable.
scanf("%d", &pinNumber);
Note: There’s an ampersand & before the variable names in the arguments. The program will crash if there’s a missing & sign.
Example
In this example, the program will prompt the user to enter a number with "Add tip amount: ". Then the user can enter a number in the terminal, press Enter, and the number will get stored in the variable tip.
#include <stdio.h>int main() {float tip = 0.0;printf("Add tip amount: ");scanf("%f", &tip);printf("You gave a tip of $%.2f", tip);return 0;}
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours