krbu
krbu

Reputation: 67

Trouble with do-while-loop

I'm trying to write a program which calculates prime numbers and I have issues with a do-while-loop I am using.

Code:

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

If I input values to trigger Lower Limit >= Upper Limit it triggers the first error properly, but doesn't repeat the do-while-loop afterwards and doesn't close the program (return(0)) either... So the program is not repeating the do-while-loop, neither is the program exiting it. I really have no clue what it is actually doing there.

If I input values to trigger !(cin >> lower_limit) || !(cin >> upper_limit) ("adfd" or the like) the whole program just goes mental and rapidly repeats the do-while-loop, even ignoring the cin >> lower_limit; and cin >> upper_limit; statements.

Does anybody have an idea that can help me out?

Cheers!

Upvotes: 1

Views: 392

Answers (1)

Abhishek Bansal
Abhishek Bansal

Reputation: 12715

One point is that if you get invalid input, you need to clear the error state by:

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

Your loop should be changed to something like:

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

Upvotes: 1

Related Questions