scanf() in a do-while loop causes infinite loop even with test of input

本小妞迷上赌 提交于 2020-01-11 12:20:27

问题


I have this:

float a, b, c;
int isInt;
do {
    puts("Please enter three positive lengths:");
    isInt = scanf(" %f %f %f", &a, &b, &c);
} while(a <= 0 || b <= 0 || c <= 0 || isInt != 3);

Let's say my input is 1 2 f, then a == 1, b == 2, and c == 0. Even more, isInt == 2, which makes me wonder why it doesn't loop normally again...?


回答1:


The problem in your code is what you do (more specifically, what you do not do) when scanf(...) returns a number other than 3.

Currently, your code continues asking for input and loops on, without taking anything from the input buffer. This, of course, makes your program go into an infinite loop.

In order to fix this issue your code should read and ignore all input up to the next '\n' character. This would make sure that each loop iteration makes some progress.

do {
    puts("Please enter three positive lengths:");
    isInt = scanf(" %f %f %f", &a, &b, &c);
    if (isInt == EOF) break; // Make sure EOF is handled
    if (isInt != 3) {
        scanf("%*[^\n]");
        a = b = c = -1;
        continue;
    }
} while(a <= 0 || b <= 0 || c <= 0);

Demo.



来源:https://stackoverflow.com/questions/35003965/scanf-in-a-do-while-loop-causes-infinite-loop-even-with-test-of-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!