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.
You might remember the scanf()
function from our previous discussions. The scanf()
function is used to receive inputs from the user so that we as programmers would be able to manipulate it to solve a specific problem.
The syntax of the scanf()
function is as follows:
scanf("format-specifiers", &var1, &var2, …);
Accepts:
“format-specifiers”
: representing a string containing format specifiers or conversion specification used to receive inputs.&var1, &var2, …
: representing addresses of multiple variables (names are dummy).The syntax proves that the scanf()
function has the capability to receive multiple inputs. Also, it returns the number of inputs it receives correctly. This information can be valuable in handling errors. Don’t worry! Once we discuss some examples, we will quickly grasp the concept.
Let’s consider some examples to understand how we can use the scanf()
function to accept multiple inputs from the user.
The following program accepts two numbers from the user and displays the sum:
#include <stdio.h>
int main()
{
int a, b, sum, n;
printf("Enter two numbers: ");
n = scanf("%d%d", &a, &b);
if (n < 2) {
printf("We need at least two integers to calculate the sum. Try again!");
return 1;
}
sum = a + b;
printf("Sum: %d", sum);
return 0;
}
Output:
Enter two numbers: 10 20
Sum: 30
Note
The text "Enter two numbers: "
is displayed on the screen. 10 and 20 are the inputs provided by the user, and sum: 30
represents the final output.
You might have noticed something unusual in the above program. I have written the statement n = scanf("%d%d", &a, &b);
. This declaration shows that I am trying to store the return value of the scanf()
function in the variable n. But what does the scanf()
function return?
The scanf()
function, in addition to its usual work of receiving values, also returns the count of the inputs it successfully reads. Our program has produced the correct output because the scanf()
function has returned value 2, which is making the condition in the if statement false. Due to this reason, the sum is calculated properly.
What if the user has provided incorrect input(s) like the following?
Enter two numbers: 10 c
The scanf()
function has two %d
s as format specifiers. Therefore, it can only accept two integers. The first integer can be read without any problem, but in place of the second integer, it finds the character c. This character cannot be read as an integer; therefore, the scanf()
function would be able to read only one integer, and therefore it returns 1. The if condition will be satisfied, and we will see the following output:
We need at least two integers to calculate the sum. Try again!
That’s a neat message, and it informs the user that something is wrong with the inputs provided. It’s a common practice to handle errors in the user inputs like this.
We can accept integer inputs from the user, manipulate them, and produce the desired result. But honestly, this is not the only type of data we can accept from the user. In this section, we will learn how to accept float, character, and string type values from the user.
To accept a float value, we need to pass in %f
as the format specifier.
#include <stdio.h>
int main()
{
float percentage;
printf("Enter the percentage value: ");
scanf("%f", &percentage);
printf("I have secured %f%% marks.", percentage);
return 0;
}
Output:
Enter the percentage value: 56.89
I have secured 56.89% marks.
Assuming the input provided by the user is 56.89. This value will be stored in the variable percentage, which is a float variable, and displayed on the screen with the message as shown.
In the same way, we can read multiple floats by placing multiple %f format specifiers as needed.
To read a character, use the %c
format specifier as shown:
#include <stdio.h>
int main()
{
char grade;
printf("Enter your grade: ");
scanf("%c", &grade);
printf("I have secured %c grade.", grade);
return 0;
}
Output:
Enter your grade: C
I have secured C grade.
There is an important concept that I would like to mention through an example. Consider the following program:
#include <stdio.h>
int main()
{
char gradeM, gradeS;
printf("Enter your grade in Maths: ");
scanf("%c", &gradeM);
printf("Enter your grade in Science: ");
scanf("%c", &gradeS);
printf("I have secured %c grade in Maths and %c grade in Science.", gradeM, gradeS);
return 0;
}
Output:
Enter your grade in Maths: A
Enter your grade in Science: I have secured A grade in Maths and grade in Science.
Something is not right. When you run this program, you will notice that it allows you to enter just one input. Let us consider the input is A. After hitting enter, “Enter your grade in Science: “
will be displayed, but it does not allow you to enter anything. Instead, you will observe this incomplete message: “I have secured A grade in Maths and grade in Science.”
Why is this happening? Let’s find the root cause.
The first character is received correctly, and as soon as we hit enter, the problem arises. This is because when we hit enter, we provide a special character as the input, which is the newline character (represented by ‘\\n
’). This character is received by the second scanf()
function and is stored in the variable gradeS
. It is a whitespace character, which explains why we were unable to provide the second input.
To avoid this problem, we can add a space before %c
in the second scanf()
function. This tells the scanf()
function to ignore all whitespace characters and only accept non-whitespace characters.
So, we need to rewrite our program as follows:
#include <stdio.h>
int main()
{
char gradeM, gradeS;
printf("Enter your grade in Maths: ");
scanf("%c", &gradeM);
printf("Enter your grade in Science: ");
scanf(" %c", &gradeS); // space is added before %c
printf("I have secured %c grade in Maths and %c grade in Science.", gradeM, gradeS);
return 0;
}
Output:
Enter your grade in Maths: A
Enter your grade in Science: D
I have secured A grade in Maths and D grade in Science.
The following program will also produce the desired result:
#include <stdio.h>
int main()
{
char gradeM, gradeS;
printf("Enter your grade in Maths and Science: ");
scanf("%c %c", &gradeM, &gradeS); // space between the format specifiers will ignore all whitespace characters.
printf("I have secured %c grade in Maths and %c grade in Science.", gradeM, gradeS);
return 0;
}
Output:
Enter your grade in Maths and Science: A D
I have secured A grade in Maths and D grade in Science.
If you don’t know already, a whitespace character can be a tab, newline, or space. Whitespace is the term used for these characters.
To read a string, %s
as the format specifier can be used, and the variable can be passed without an ampersand (&
).
#include <stdio.h>
int main()
{
char name[20];
printf("Please enter your name: ");
scanf("%s", name); // No need of & in front of the variable.
printf("My name is %s.", name);
return 0;
}
Output:
Please enter your name: Saurabh
My name is Saurabh.
Why is an ampersand not needed?
An array (or a list) holds a string, which is a series of characters. We have given the array a name and said that it can hold up to 20 characters. So, the array can hold the string “Saurabh”.
The name of an array refers to the address of its first element (not a value), so passing the name without an ampersand is enough.
In the same way, you can accept multiple strings as well. That’s not a problem.
&
: To the scanf()
function, you always have to provide the address of the variable where you want to store the data. This can be done through an ampersand symbol (string input is an exception).%c
without a space: there is the possibility that a newline is read by the scanf()
function as the character. To avoid this, add space before %c
.scanf(”%s”, &str);
: As mentioned before, do not use &
before a string variable.scanf()
function can accept multiple inputs. Multiple variables with the same number of format specifiers are needed to accept inputs properly.scanf()
function. At least on paper, a single scanf()
function can receive an infinite number of inputs.Q1. What is the output of the following program?
#include <stdio.h>
int main()
{
int x, y;
printf("Enter the two numbers: ");
scanf("%d%d", &x, &y);
printf("%d", x + y);
return 0;
}
A. 1020
B. 30
C. Garbage value
D. Compilation error
A. Option (B) is the correct option. The program correctly receives two values from the user and displays the addition of those values.
Q2. Which of the following statements about the scanf()
function is TRUE? (Note: multiple options can be correct.)
A. The scanf()
function can accept an unlimited number of inputs.
B. All variables passed to the scanf()
must have &
before them.
C. The scanf()
function returns the number of successful inputs read.
D. We cannot read strings using scanf()
.
A. Options (A) and (C) are the correct options. Option (B) is incorrect because strings don’t need &, and option (D) is incorrect because scanf()
can read strings too.
Q3. What is the correct way to accept a float and a character using scanf()
?
A. scanf(”%f %c”, &percentage, grade);
B. scanf(”%f %c”, percentage, &grade);
C. scanf(”%f %c”, percentage, grade);
D. scanf(”%f %c”, &percentage, &grade);
A. Option (B) is correct. Both float
and char
need &
to store the input.
Q4. Why is it a bad idea to write scanf(”%s”, &str);
when str
is a character array?
A. This is because the name of the character array itself gives the address of the string, so there is no need to use &
before it. Using &
before the name of a character array in the scanf()
function is an undefined behavior.
Q5. Can we write scanf(”%d%d%d%d%d”, &a, &b, &c, &d, &e);
and input values on different lines as shown?
Input:
10 20
30
40 50
A. Yes. scanf()
considers newlines as whitespaces, so you can absolutely provide inputs in newlines.
Leave a comment