3

这是 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 输入字符不会运行。

4

1 回答 1

5

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

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

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

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

于 2013-02-01T03:28:43.760 回答