do-while-loop有问题

时间:2013-12-21 10:47:06

标签: c++ loops cin do-while

我正在尝试编写一个计算素数的程序,而且我正在使用的do-while-loop存在问题。

代码:

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    unsigned long int lower_limit;
    unsigned long int upper_limit;

    cout << "\n" << "Program calculates prime numbers in a given range between 2 and 4.294.967.295.";
    cout << "\n" << "Input range in which prime numbers are to be calculated... ";

    do
    {
        cout << "\n\n" << "Lower Limit:\t";     cin >> lower_limit;     
        cout << "\n" << "Upper Limit:\t";       cin >> upper_limit;     

        if(lower_limit >= upper_limit)
        {
            cout << "\nInvalid Input: Value of Upper Limit has to be bigger than value of Lower Limit.";
            cout << "\nSelect new numbers.";
        }

        if(!(cin >> lower_limit) || !(cin >> upper_limit))
        {
            cout << "\nInvalid Input: Values of Lower Limit and Upper Limit have to be integers.";
            cout << "\nSelect new numbers.";
        }

    }while(lower_limit >= upper_limit || !(cin >> lower_limit) || !(cin >> upper_limit));

    return(0);
}

如果我输入值来触发Lower Limit >= Upper Limit,它会正确触发第一个错误,但之后不会重复执行do-while循环,也不会关闭程序(return(0))...因此程序不会重复执行do-while-loop,程序也不会退出。我真的不知道它在那里做了什么。

如果我输入值来触发!(cin >> lower_limit) || !(cin >> upper_limit)(“adfd”等),整个程序就会精神错乱并快速重复执行do-while循环,甚至忽略cin >> lower_limit;和{{1语句。

有人有想法可以帮助我吗?

干杯!

1 个答案:

答案 0 :(得分:1)

有一点是,如果输入无效,则需要通过以下方式清除错误状态:

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

你的循环应该改为:

do
{
  while ( !(cin >> lower_limit >> upper_limit) ) {
    cout << "Invalid input, Please re-enter\n";      
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  }

  if(lower_limit >= upper_limit)
  {
    cout << "\nInvalid Input: Value of Upper Limit has to be bigger than value of Lower Limit.";
    cout << "\nSelect new numbers.";
  }


} while(lower_limit >= upper_limit);