开发者

Second scanf is not working

i am having trouble with this c language code:

 char st[2];

 printf("enter first value:");
 scanf("%c", &st[0]);

 printf("enter second value:");
 scanf("%c", &st[1]);

So my computer didn't ask me to enter the开发者_开发问答 second value, I mean to say that it only print the first printf statement then I enter a character and then it only prints the second printf statement and program end without taking the second input.

Please help. What's wrong with this code?

-Thanks in advance.


Well it did. The character(s) produced by the ENTER key is present in the buffer already.


use fflush(stdin); function before the second scanf();. It will flush the ENTER key generated after first scanf();. Actually, your second scanf() is taking the ENTER as its input and since scanf terminates after getting an ENTER, it is not taking anything else by your side.


I think your problem is the second scanf is receiving the "Enter" key press.


You're getting the implicit newline you entered as the second character, i.e. st[1] is getting the value '\n'. An easy way to fix this is to include the newline in the expected format string: scanf("%c\n", &st[0]);


Change

scanf("%c", &st[0]);

to this

scanf(" %c", &st[0]);

That's a shotty answer (no error checking or anything) but its quick and easy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜