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

use*_*243 3 c loops for-loop 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;
}
Run Code Online (Sandbox Code Playgroud)

每次程序运行第一次scanf工作正常,但在第二次通过循环时,scanf输入一个字符不会运行.

Neo*_*low 5

前添加一个空格%cscanf.这将允许scanf在阅读之前跳过任意数量的空格choice.

scanf(" %c", &choice); 是唯一需要的改变.

添加fflush(stdin);之前scanf("%c", &choice);也会有效.fflush在通过scanf读取下一个输入之前,call将刷新输入缓冲区的内容.

在的情况下,scanf(" %c", &choice);即使仅存在在输入读缓冲器的单个字符,scanf将解释该字符为一个有效的用户输入,并与执行继续.scanf的错误使用可能会导致一系列奇怪的错误[就像在while循环中使用时的无限循环].