Accepting Multiple Inputs
In this lesson, we will understand what happens when a user gives several inputs, and how the scanf() function manages them all.
In this lesson, we will understand what happens when a user gives several inputs, and how the scanf() function manages them all.
It is common for the scanf()
function to receive multiple inputs simultaneously, as demonstrated in the example program below.
#include <stdio.h>
int main()
{
int x, z;
float y;
scanf("%d%f%d", &x, &y, &z);
printf("x = %d, y = %.2f, and z = %d", x, y, z);
return 0;
}
Let’s imagine that the user has entered the values for x, y, and z as follows:10 2.56 -3
Then, the output will be:
10 2.56 -3
x = 10, y = 2.56, and z = -3
Process returned 0 (0x0) execution time : 11.607 s
Press any key to continue
Note that the first line is the input line.
The format string used in the scanf()
function above is a commonly used method to accept multiple inputs. The format specifiers in the format string are closely packed together. However, even though the user has entered the inputs separated by spaces, scanf()
simply ignores these spaces and stores the data in the corresponding variables.
In this specific example, the first input value is assigned to the variable x because it appears immediately after the format string. The second input value, which is a floating-point number, is assigned to the variable y. Finally, the last input value is assigned to the variable z.
It’s important to note that the order of the variables matters. The number of format specifiers in the format string must match the number of variables, and there should be no mismatch in data types. To avoid unexpected results, the types of the variables, inputs, and format specifiers should all match appropriately.
Leave a comment