Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
In the C programming language, scanf is a function that reads formatted data from stdin (i.e, the standard input stream, which is usually the keyboard, unless redirected) and then writes the results into the arguments given.
This function belongs to a family of functions that have the same functionality but differ only in their source of data. For example, fscanf gets its input from a file stream, whereas sscanf gets its input from a string.
The scanf function has the following prototype/signature:
int scanf( const char *format, ... );
A simple type specifier consists of a percent (%) symbol and an alpha character that indicates the type. Below are a few examples of the type specifiers recognized by scanf:
The function works by reading input from the standard input stream and then scans the contents of "format" for any format specifiers, trying to match the two. On success, the function writes the result into the argument(s) passed.
For example, if the function call is
scanf( "%c%d", &var1, &var2 );
and the user types "a1", the function will write "a" into "var1" and "1" into "var2". If the function call, however, is
scanf( "%x", &var );
the same input will be read as the hexadecimal number "a1," which is 161 in decimal.
The function returns the following value: