C Language | Introduction to C | Data Input with scanf()
This article explains how to receive values entered from a keyboard with scanf().
Receiving User Input
The programs so far have assigned constants to variables. In real programs, variables are useful for values that change dynamically while the program runs.
How can a program receive dynamic values? Reading data from a disk file is one option. For example, text loaded from a file and displayed on the screen changes at runtime. Reading files is an intermediate topic, so it is explained later.
A simpler option is keyboard input. It makes programs more useful and easier to test. Use scanf() to receive keyboard input. scanf() is an input counterpart to printf() and stores keyboard input in specified variables.
scanf() Function
int scanf("format" , &variableName);
The first argument is a format string. The remaining arguments specify variables that receive input values. Format specifiers are similar to those used by printf(): use %d for an integer and %c for a character. Place & before the variable name.
The & is required because the function needs the address of the variable. Pointers explain this in detail. For now, remember to place & before a variable passed to scanf().
scanf() returns the number of fields successfully converted and assigned.
Code 1
#include <stdio.h>
int main() {
int iVar = 0;
printf("정수를 입력해 주세요. > ");
scanf("%d" , &iVar);
printf("입력한 수는 %d입니다.\n" , iVar);
return 0;
}
When Code 1 runs, it requests a value. If you enter an integer, the value is assigned to iVar and displayed. If the input cannot be converted correctly, no value is assigned.
Production programs rarely use scanf() for complex input because robust error handling is difficult. They often read text with another standard-input function, inspect the string, and convert it appropriately. This book uses scanf() to keep introductory examples simple.