While-loop ignores scanf the second time

前端 未结 3 2064
醉话见心
醉话见心 2020-11-27 08:49
#include 

int main ()
{
    char loop=\'y\';
    while(loop != \'n\') {
        printf(\"loop? \");
        scanf(\"%c\", &loop);
        if(loop         


        
相关标签:
3条回答
  • 2020-11-27 08:54

    Make sure the scanf discards the newline. Change it to:

    scanf(" %c", &loop);
           ^
    
    0 讨论(0)
  • 2020-11-27 09:03

    One solution can be the use fflush(stdin) after the scanf() statement to clear the input buffer.

    0 讨论(0)
  • 2020-11-27 09:05

    You probably had to enter a newline so the input goes to your program, right? The second time your loop executes it reads that newline character, which was "waiting" to be read and automatically exits the loop ('\n' != 'y'). You can make scanf ignore whitespace by using this format string instead:

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