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

牧云@^-^@ 提交于 2019-12-02 04:15:57

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.

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