Reputation: 175
the following code as expected should accept two char values from user. but it just accepts one value of ch1 and then prints "hello".
#include<stdio.h>
int main()
{
char ch1, ch2;
printf("Enter a char: ");
scanf("%c",&ch1);
printf("Enter second char: ");
scanf("%c",&ch2);
printf("Hello");
return 0;
}
it is not accepting the second value for ch2..what can be the possible reason? As far as i think, it should accept 2 characters.
Upvotes: 0
Views: 43
Reputation: 121427
It just accepts only one char because the the first call to scanf()
left a newline in the input stream.
You can ignore it with:
scanf(" %c",&ch2); // note the leading space.
This will ensure the newline from the previous input will be ignored. A white-space in the format string tells scanf()
to ignore any number of white-space characters. You might also want to check the return value of scanf()
calls in case it failed.
From scanf()
:
. A sequence of white-space characters (space, tab, newline,
etc.; see isspace(3)). This directive matches any amount of
white space, including none, in the input.
Upvotes: 1