为什么我在c ++中的while循环无法正常运行?

时间:2014-09-25 20:40:21

标签: c++ while-loop

我只是编程的新手,我试图编写一个while循环,只要输入(num)不是一个不以零结尾的整数。当我输入一个以零结尾的数字时,程序会正确地运行循环,但是当我输入一些废话,例如rofl时,程序只打印The input is not valid.并且不会重复环。我试图寻找解决方案,但一小时后我仍然陷入困境。有人可以帮我吗?太多了!

void rev_sum() {
    int num;
    int a = 1;
    while (a < 2) {
        cout << "Please input a natural number without zero at the end:\n";
        cin >> num;
        if (!cin) {
            cout << "The input is not valid.\n";
            cin.clear();
            cin.ignore(INT_MAX);
        }
        if (num % 10 == 0) {
            cout << "The number cannot have zero at the end\n";
        } else {
            cout << "gj\n";
            break;
        }
    }
}

5 个答案:

答案 0 :(得分:3)

尝试替换

cin.ignore(INT_MAX);

使用

cin.ignore(numeric_limits<streamsize>::max(), '\n');

并改变

if (num % 10 == 0)

else if (num % 10 == 0)

您的最终代码应如下所示:

void rev_sum() {
    int num;
    int a = 1;
    while (a < 2) {
        cout << "Please input a natural number without zero at the end:\n";
        cin >> num;
        if (!cin) {
            cout << "The input is not valid.\n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
        else if (num % 10 == 0) {
            cout << "The number cannot have zero at the end\n";
        } else {
            cout << "gj\n";
            break;
        }
    }
}

答案 1 :(得分:1)

if (num % 10 == 0) {

可能是

else if (num % 10 == 0) {

否则其他情况可能会被执行

答案 2 :(得分:1)

你在循环开始时设置a = 1然后永远不会改变a这意味着离开你的while循环的唯一方法就是你点击break语句。如果你的循环没有循环,那么它必须被卡在某处。我不熟悉语句if (!cin)cin.ignore(...),因此这些是检查(或更改)的最大嫌疑人。语句cin >> num;无论他们输入什么都会完成,因此您可以查看“#”数字是什么?等于你输入&#34; rofl&#34;。然后在失败后,您仍然使用num,因此您正在处理此无意的条目。您可以在continue;之后添加cin.ignore(...)以跳回while循环的顶部并再次提出问题。您还可以在while循环后打印一些内容,以便知道何时离开。

尽管如此,我绝不会相信用户输入可接受的信息,我绝不相信cin会为我处理它。就个人而言,我会使用cin.getline(buffer,buffer_size)将cin读为字符串;然后我会向用户抱怨如果他们填充缓冲区或给了我一些不是整数的东西(你可以用scanf()这样的函数检查)。然后你可以准确地回吐他们给你的东西,你可以具体说明你的抱怨。

答案 3 :(得分:0)

cin.ignore(numeric_limits<streamsize>::max())

答案 4 :(得分:0)

如果输入有效,只检查数字是否以0结尾是没有意义的。

void rev_sum() {
    int num;
    int a = 1;
    while (a < 2) {
        cout << "Please input a natural number without zero at the end:\n";
        cin >> num;
        if (!cin) {
            cout << "The input is not valid.\n";
            cin.clear();
            cin.ignore(INT_MAX);
        } else {
            if (num % 10 == 0) {
                cout << "The number cannot have zero at the end\n";
            } else {
                cout << "gj\n";
                break;
            }
        }
    }
}
相关问题