The scanf() function in C is used for reading formatted input from the standard input (keyboard) or from a specified file stream. It is part of the standard input-output library stdio.h.
Syntax of scanf function is
scanf ("format string", argument list);
Format string specifies the format of the input. It may contain format specifiers which represent the type and format of the input expected. The format string must be a text enclosed in double
quotes. It contains the information for interpreting the entire data for
connecting it into internal representation in memory.
Example: integer (%d) , float (%f) , character (%c) or string (%s).
The argument list contains a list of variables each preceded by the address list and separated by comma. The number of argument is not fixed; however corresponding to each argument there should be a format specifier. Inside the format string the number of argument should tally with the number of format specifier.
Example: if i is an integer and j is a floating point
number, to input these two numbers we may use
scanf ("%d%f", &i, &j);
Example:
#include <stdio.h>
int main() {
int num;
float f_num;
// Reading integer and float from standard input
printf("Enter an integer and a float: ");
scanf("%d %f", &num, &f_num);
printf("You entered: %d and %f\n", num, f_num);
return 0;
}
scanf() is powerful but can be tricky to use correctly. Carefully crafting the format string and handling return values and buffer sizes can help avoid common pitfalls.