循环在第一次之后跳过一个scanf语句 [英] Loop skips a scanf statement after the first time

查看:133
本文介绍了循环在第一次之后跳过一个scanf语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是main()的代码:

pre $ int $ $ $ $ $ $ $ $漂浮英亩[20];
浮动蒲式耳[20];
float cost = 0;
float pricePerBushel = 0;
float totalAcres = 0;
字符选择;
int counter = 0;

(counter = 0; counter< 20; counter ++)
{
printf(你想进入另一个农场吗?

scanf(%c,& choice);

if(choice =='n')
{
printf(in break);
break;
}

printf(输入亩数:);
scanf(%f,& acres [counter]);

printf(输入蒲式耳数:);
scanf(%f,& bushels [counter]);

}


return 0;



$ b每次程序运行通过第一次scanf都能正常工作,

解决方案

%c之前添加一个空格在 scanf 中。在读取 choice 之前,这将允许 scanf 跳过任意数量的空格。



scanf(%c,& choice); 是唯一需要的更改。


$ b

scanf(%c,& choice)之前添加 fflush(stdin); ; 也可以使用。

如果 scanf(%c,& choice); 即使输入读缓冲区中只有一个字符 scanf 会将此字符解释为有效的用户输入并继续执行。不正确的使用scanf可能会导致一系列奇怪的错误[如在中使用无限循环,而循环]。


Here is the code for main():

int main (void)
{
float acres[20];
float bushels[20];
float cost = 0;
float pricePerBushel = 0;
float totalAcres = 0;
char choice;
int counter = 0;

for(counter = 0; counter < 20; counter++)
{   
    printf("would you like to enter another farm? "); 

    scanf("%c", &choice);

    if (choice == 'n')
    {
        printf("in break ");
        break;
    }

    printf("enter the number of acres: ");
    scanf("%f", &acres[counter]);

    printf("enter the number of bushels: ");
    scanf("%f", &bushels[counter]);

}


return 0;
}

Every time the program runs through the first scanf works fine but on the second pass through the loop the scanf to enter a character does not run.

解决方案

Add a space before %c in scanf. This will allow scanf to skip any number of white spaces before reading choice.

scanf(" %c", &choice); is the only change required.

Adding an fflush(stdin); before scanf("%c", &choice); will also work. fflush call will flush the contents of input buffer, before reading the next input via scanf.

In case of scanf(" %c", &choice); even if there is only a single character in the input read buffer, scanf will interpret this character as a valid user input and proceed with execution. Incorrect usage of scanf may result in a series of strange bugs [like infinite loops when used inside while loop].

这篇关于循环在第一次之后跳过一个scanf语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆