循环在第一次之后跳过scanf语句

这是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); 是唯一需要的改变。

添加fflush(stdin);scanf("%c", &choice);之前scanf("%c", &choice); 也会工作。 fflush调用将刷新输入缓冲区的内容,然后通过scanf读取下一个输入。

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