Reputation: 61
Below is a program which accepts two character and prints them
#include<stdio.h>
int main()
{
char c1, c2;
printf("\n Enter characters one : ");
scanf(" %c", &c1);
printf("\n Enter character two : ");
scanf("%c", &c2);
printf("\n The the characters are %c and %c ", c1, c2);
return 0;
}
Now one output instance is :-
Enter two characters : a
The the characters are a and
The problem is that I haven't given any space between two format specifier %c
Here I pressed 'a' and then '\n' which gets stored into c1 and c2 respectively. And thus I got output which was not accepted.
I know how to correct this problem.
Now I make the same program for the integers :-
#include<stdio.h>
int main()
{
int a, b;
printf("\n Enter two numbers : ");
scanf("%d%d", &a, &b);
printf("\n The two numbers are %d and %d ", a, b);
return 0;
}
Here we will not found any problem.
I think this time we didn't encounter problem because the second input we give is '\n'
or space which is not any integer and thus we get a failure in the reading from the scanf()
function so the input buffer is still active and if we press the next input as integer then it gets stored into variable 'b'
.
Can you tell me the reason which I thought is correct or not?
Now if it is correct then what will happen if I press again a character. Then also it should not get stored into the variable 'b'
but this time 0 gets stored into variable 'b'
.
So my question is that what is the reason for proper behavior of the program when I'm trying to make the same program with %d
Upvotes: 1
Views: 1861
Reputation: 134326
To answer your question, let's have a look at C11
standard, chapter §7.21.6.2
Input white-space characters (as specified by the
isspace
function) are skipped, unless the specification includes a[
,c
, orn
specifier.
So, when you have a newline
('\n'
, which is indeed a white-space character) left in the input buffer,
in case of scanf("%c", &charVar);
, the newline is considered as the input, so the second scanf skips asking for the input from user.
in the case of scanf("%d", &intVar);
the leftover newline
is skipped and it wait for the integer input to appear, so it stops and asks the user for the input.
However, FWIW, in later case, if you input a non-whitespace character and press ENTER, the char input will be considered as an input, causing a matching failure.
Related
[...] If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure.
Upvotes: 3
Reputation: 1722
It's reading the new line as the newline is a character. Simply changing scanf("%c", &c2);
to scanf(" %c", &c2);
will make it work.
So in your code: #include
int main()
{
char c1, c2;
printf("\n Enter characters one : ");
scanf(" %c", &c1);
printf("\n Enter character two : ");
scanf(" %c", &c2);
printf("\n The the characters are %c and %c ", c1, c2);
return 0;
}
Upvotes: 0