C: Do-While Loop Repeating Too Much!

大憨熊 提交于 2019-12-02 08:44:01

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.

You want

do
{

} while (condition);

As your forgot the semicolon, you get:

do
{
    ....
}

while(condition)
    do something else;

You could have noticed that just by auto-indenting your code in an editor like I did on your question.

Also when you do some scanf you should rather include the \n in the format specification.

First of all, # include <stdio.h> and use getc(stdin) to get a character. It'll help you to prevent cursor from moving and putting unnecessary characters to console. Secondly, write the welcome message before the loop.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!