简体   繁体   English

C中的无限循环不会停止scanf

[英]Infinite loop in C wont stop for scanf

I started learning C and i am still at simple programs but with a ton of errors :/ The following code once it catches the wrong input (in the else statement) will continue running and it wont stop for the next scan... why is that happening? 我开始学习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;
}

If you are entering anything else than a numerical value then it will not read by scanf and live there for infinite time causing infinite loop. 如果您输入的不是数字值,则scanf不会读取它,并且将其在其中存在无限长的时间,从而导致无限循环。 You must have to flush the input buffer. 您必须必须刷新输入缓冲区。 Place this after the else statement: 将其放在else语句之后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM