User Input

User Input

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;
}
Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn C on Codecademy