【问题标题】:Loop skips a scanf statement after the first time循环在第一次之后跳过一个 scanf 语句
【发布时间】:2013-01-16 08:15:54
【问题描述】:

这是 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 loops for-loop scanf


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 2014-10-27
    • 1970-01-01
    相关资源
    最近更新 更多