Second scanf is not working

前端 未结 5 1652
旧巷少年郎
旧巷少年郎 2020-12-06 19:36

i am having trouble with this c language code:

 char st[2];

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

 printf(\"enter second value:\");
         


        
相关标签:
5条回答
  • 2020-12-06 20:01

    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.

    0 讨论(0)
  • 2020-12-06 20:03

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

    0 讨论(0)
  • 2020-12-06 20:03

    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 讨论(0)
  • 2020-12-06 20:05

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

    0 讨论(0)
  • 2020-12-06 20:05

    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]);

    0 讨论(0)
提交回复
热议问题