这是 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;
}
每次程序运行第一次 scanf 时都工作正常,但在第二次循环中,用于输入字符的 scanf 不会运行。
前面加一个空格%c
in scanf
。这将允许scanf
在阅读之前跳过任意数量的空格choice
.
scanf(" %c", &choice);
是唯一需要的更改。
添加一个fflush(stdin);
before scanf("%c", &choice);
也会起作用。fflush
在通过 scanf 读取下一个输入之前,调用将刷新输入缓冲区的内容。
的情况下scanf(" %c", &choice);
即使输入读取缓冲区中只有一个字符,scanf
会将此字符解释为有效的用户输入并继续执行。不正确地使用 scanf 可能会导致一系列奇怪的错误 [比如在内部使用时出现无限循环while
loop].
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)