C: Do-While Loop Repeating Too Much!

前端 未结 3 1479
醉梦人生
醉梦人生 2021-01-27 17:05

I have a small program that which is confusing me. I am trying using a loop to take input from user. In case input is wrong, it is repeated again but if it is right, it exits.

3条回答
  •  独厮守ぢ
    2021-01-27 18:09

    Because you have given scanf three characters to process. It removes first first character the first time it calls scanf getting 'a', but still has 'bc' left in the stdin buffer.

    You need to check for leftover stuff in your buffer before you look for input again. And I'd avoid flushing the stdin buffer because it's undefined behavior. (http://www.gidnetwork.com/b-57.html)

    You can read the remaining characters and discard them with

    do{  
        scanf("%c", &user_status);  
    }while(user_status!='\n'); //This discards all characters until you get to a newline
    

    right after you read the character you want.

提交回复
热议问题