do-while循环中的scanf()会导致无限循环,即使测试输入也是如此 [英] scanf() in a do-while loop causes infinite loop even with test of input

查看:198
本文介绍了do-while循环中的scanf()会导致无限循环,即使测试输入也是如此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

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);

假设我的输入为 1 2 f ,则 a == 1 b == 2 c == 0 。甚至还有 isInt == 2 ,这让我想知道为什么它不能再次正常循环...?

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

推荐答案

您的代码中的问题是 scanf(...)返回3以外的数字。

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.

为了解决此问题,您的代码应阅读并忽略直到下一个<$ c的所有输入。 $ c>'\n'字符。这样可以确保每次循环迭代都能取得一定的进展。

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);

演示。

这篇关于do-while循环中的scanf()会导致无限循环,即使测试输入也是如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆