scanf

The scanf function is used to read values of basic data types from standard input. The function has a variable number of parameters, but the first parameter is always a constant string that provides the format of the input.

The format string has either literal characters (characters that will be printed on the output) or argument specifiers, which start with the character %. There are argument specifiers to all basic data types in the C language. A quick list is the following: (the list is similar to the specifiers to the printf function)

For example, the following code will read using a format string that specifies an integer, a float, and a string variable.

int number;
float price;
char *message;
scanf("Please, type the values : %d %f %s", &number, &price, message);

Notice from the above, that contrary to the usage with the printf function, all arguments to the scanf function must be pointers. The reason is that the C language can pass values only by value, and references are simulated by the passing of pointers. Thus, if the content of variables must be modified, a pointer to the variable must be passed instead of their values.

Note: scanf is not a type safe function, in the sense that it doesn't check the exact type of the argument that is passed corresponds to the type specified in the first parameter. For example, it is legal to write

int x;
scanf("%s", &x);

and most compilers will compile this code (although some smart corpilers will at least give a warning). However, the function is treating a pointer to an integer as a pointer to a null terminated sequence of characters, which can have disastrous consequences to the program.

To avoid this kind of problems, if you are using C++ always use the iostream classes instead of scanf and their friends. If you must use C, be extra careful about arguments to scanf-like functions. Some tools, such as the "lint" program, are able to detect some cases of misuse of the scanf function.

Article created on 2008-08-19 22:09:55

Post a comment