【问题标题】:Infinite loop in C wont stop for scanfC中的无限循环不会停止scanf
【发布时间】:2014-08-26 12:48:48
【问题描述】:

我开始学习 C,我仍然在简单的程序中,但是有很多错误:/ 以下代码一旦捕获到错误的输入(在 else 语句中)将继续运行,并且不会停止下一次扫描......为什么会发生这种情况?

const float inch_to_cm = 2.54;

int main()
{
    bool run = true;
    float usr_input;
    while(run){
        printf("Please enter the inches: ");
        if (scanf("%f", &usr_input) == 1){
            printf("Result: %4.2f \n", inch_to_cm*usr_input);
            run = false;
        }
        else{
            printf("I asked for a number!\n");
        }
    }

    return 0;
}

【问题讨论】:

  • 你输入的错误是什么?
  • 如果你刚开始学习 C,你可能should not be posting on this website。一旦您准备好向 Stack Overflow 发布有意义的贡献,您将不再“刚刚开始学习 C”。
  • 你需要消耗一个无效的输入。

标签: c loops scanf


【解决方案1】:

如果您输入的不是数值,那么scanf 将不会读取它并在那里无限期地存在,从而导致无限循环。您必须刷新输入缓冲区。将其放在else 语句之后:

int c;
while((c = getchar()) != '\n' && c != EOF);

【讨论】:

    猜你喜欢
    • 2015-03-15
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多