0

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.

4
  • Wouldn't you want cin.eof()? Commented Jan 17, 2014 at 4:02
  • what does the eof() function do? Commented Jan 17, 2014 at 4:02
  • It explains that on the page I linked. Commented Jan 17, 2014 at 4:03
  • Not directly related, but you will soon notice that (9/5) is exactly the same as 1 (since integer division ignores remainders). Probably easiest to just type 1.8. Commented Jan 17, 2014 at 4:45

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

I've tried doing that, but if I enter a non integer/double input, it simply goes into an infinite loop.
@Retrosaur, see my edit for improved code along with some comments/explanations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.