yuritsuki
yuritsuki

Reputation: 242

Checking for proper input leads to infinite loop

Here's the code snippet:

#include <iostream>

using namespace std;

int main ()
{
    double degree;

    do {
        cout << "Enter a temperature in degrees Celsius: ";
        cin >> degree;
    } while (cin.fail());


    //reassigns degree to conversion to farenheit
    degree = degree * (9/5) + 32;

    cout << "Your temperature in degrees Farenheit is: " << degree;
    return 0;
}

If the input is invalid, the program ends up into an infinite loop, constantly repeating the first cout.

I'm kinda new to C++, and I"m not sure if this is just the compiler acting wonky, or if it's something on my part.

Upvotes: 0

Views: 73

Answers (1)

shuttle87
shuttle87

Reputation: 15934

This happens because cin.fail() doesn't do what you think it does. cin.fail() tests for errors in input. The eof (end of file) is not an error in input as far as cin.fail() is concerned.

Instead you might want to rewrite as:

#include <iostream>

using namespace std;

int main ()
{
    double degree;

    while( (cout << "Enter a temperature in degrees Celsius: ")
            && !(std::cin >> degree)) {
        cout << "you entered in the wrong type, please try again" << endl;
        cin.clear();// clear error flags from cin
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); //extracts characters from the stream and discards them until a newline is found 
    }


    //reassigns degree to conversion to farenheit
    degree = degree * (9.0/5) + 32; //need to do floating point division here

    cout << "Your temperature in degrees Farenheit is: " << degree;
    return 0;
}

See this link for more info: http://www.cplusplus.com/reference/ios/ios/fail/

Upvotes: 2

Related Questions