Concept

How does scanf() read integer, character, and floating-point input in C?

ComputerScienceOne / Basic I/O

"15.5. Basic I/O The standard I/O library (stdio.h) contains many functions that facilitate input and output including printf() for standard output and scanf() (scan formatted input) for standard input. The printf() function works exactly as discussed in Section 2.4.3. The scanf() function works using similar placeholders as printf(). To illustrate how it works, consider the following lines of code: 1 int a; 2 printf(\"Please enter a number: \"); 3 scanf(\"%d\", &a); The printf() statement prompts the user for an input. The scanf() then executes and the program waits for the user to enter input. The user is free to start typing. When the user is done, they hit the enter key at which point the program resumes and reads the input from the standard input buffer, converts the value entered by the user into an integer and places the result in the variable a where it can now be used by the remainder of the program. A few points of interest. First, the same placeholder as printf() was used, %d for int values. However, when we “passed” the variable a to scanf() we placed an ampersand, & in front of it. This is passing the variable by reference and we’ll explore that concept further in Chapter 18, but for now just know that when using variables with scanf(), an ampersand is required. Failure to place an ampersand in front of a variable with scanf() will likely result in a segmentation fault (an illegal memory access). You can use the same placeholder, %c with scanf() to read in a single character as well. However, for floating point numbers, in particular double types, the placeholder %lf must be used (which stands for long float, a double precision number). Failure to use the correct placeholder may result in garbage results as the input will be interpreted incorrectly. Another example: 1 double x; 2 printf(\"Please enter a fractional number: \"); 3 scanf(\"%lf\", &x); Another potential problem is that scanf() expects a certain format (thus its name). If we prompt the user for a number but they just start mashing the keyboard giving non-numerical input, we may get incorrect results. scanf() will interpret the input as zero. It may be very difficult to distinguish between the case of a user actually entering"

Related Ideas

How does scanf() read integer, character, and floating-point input in C? | ComputerScienceOne | Bifalgorithm | Bifalgorithm