这是 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 不运行。
最佳答案
在scanf
中的%c
前加一个空格。这将允许 scanf
在读取 choice
之前跳过任意数量的空格。
scanf("%c", &choice);
是唯一需要的更改。
在 scanf("%c", &choice);
之前添加一个 fflush(stdin);
也可以。 fflush
调用将刷新输入缓冲区的内容,然后再通过 scanf 读取下一个输入。
在 scanf("%c", &choice);
的情况下,即使输入读取缓冲区中只有一个字符,scanf
也会将此字符解释为有效的用户输入并继续执行。 scanf 的不正确使用可能会导致一系列奇怪的错误[比如在 while
循环中使用时的无限循环]。
关于c - 循环在第一次后跳过 scanf 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14639166/