scanf() in a do-while loop causes infinite loop ev

2019-03-02 22:25发布

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...?

标签: c scanf do-while
1条回答
疯言疯语
2楼-- · 2019-03-02 23:05

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.

查看更多
登录 后发表回答