Search code examples
c++loopswhile-loopinfinite-loop

C++ Endless loop with input


I have a C++ program that takes input from the terminal, and for some reason this is producing an endless loop:

double getSideLength()
{
    cout << "Enter a side: "
double side;
cin >> side; cin.ignore( 80, '\n' );
while (side <= 0){
    cout << "Please enter a valid side. Try again: ";
    cin >> side; cin.ignore(80, '\n');
}
return side;

This produces the output:

Enter a side: invalid
Please enter a valid side. Try again:
Please enter a valid side. Try again:
Please enter a valid side. Try again:
   .... and so on. "invalid" is the only input the user made

Solution

  • as said in operator>> documentation stream get its failbit on if "The input obtained could not be interpreted as an element of the appropriate type." That happens if you enter wrong number. So you just have to clear() cin before next input. Here is code:

    double getSideLength()
    {
            double side;
            cout << "Enter a side: ";
            cin >> side;
            if (!cin)
                 cin.clear();
            cin.ignore( 80, '\n' );
            while (side <= 0){
                    cout << "Please enter a valid side. Try again: ";
                    cin >> side;
                    if (!cin)
                        cin.clear();
                    cin.ignore( 80, '\n' );
            }
            return side;
    }