在这种情况下如何防止无限循环?

时间:2014-12-05 16:02:53

标签: c++ while-loop do-while

cin>>num;
while (num < 1 || num > 3)
{
    cout << "Invalid input" << endl;
    cout << "Please insert the value range within 1 - 3... ";
    cin >> num;
}

cin为字母字符时,如何防止无限循环?当我输入字母字符时,它只会显示Invalid inputPlease insert the value range within 1 - 3...

3 个答案:

答案 0 :(得分:4)

您将结果保存到num1,但循环正在检查名为num的变量的内容。你必须在两个地方都保持一致,否则状态评估永远不会改变,不是吗?除此之外,你的逻辑看起来很好。

答案 1 :(得分:0)

试试这个: -

while (num < 1 || num > 3)
{
    if (!isdigit(num))
    cout << "Invalid input" << endl;
    else
    {
    cout << "Please insert the value range within 1 - 3... ";
    cin >> num;
    }
}

答案 2 :(得分:-2)

这个怎么样?

while (cout << "please insert a value between 1 and 3..." &&
        (cin >> num).good() &&
        (1 <= num && num <= 3))
    cout << num << endl;