multiple character input to char in C
18,752
Solution 1
We don't enter any input for second variable
That's not true, "%c"
in scanf
reads one character, after it processes the input a
, the "%c"
in the next scanf
then reads the next input character b
.
Solution 2
Because you entered 2 characters in the 1st input while the program expects just 1: the 2nd is pending until the next call to scanf
Comments
-
anuj pradhan almost 2 years
#include <stdio.h> int main(void) { char ch,ch1; scanf("%c",&ch);/*input ab here*/ scanf("%c",&ch1); printf("%c %c",ch,ch1); return 0; }
Why this produces
a b
as output. We don't enter any input for second variable but it still got assigned. Could anyone explain the behavior.You can check the output here if you want.
-
anuj pradhan almost 10 yearsBut dont you think scanf ends the input after encountering a newline character. Here We enter the new line character after typing 'ab'. Then how come b goes to second variable.
-
anuj pradhan almost 10 yearsstill the same problem.
-
Yu Hao almost 10 years@anujpradhan Add another
scanf("%c",&ch2);
after the second, you'll see the newline character inch2
.