Loop not working correctly

I have only been learning C++ for a few weeks and I have run into a problem trying to write a simple program. I am trying to write a program that converts F to C temperature. I tried to use a "Do..While" loop to make sure the user was entering a valid temperature. Everything works fine as long as I put in a valid integer. As soon as I enter a character it crashes. The debugger says "An access violation (segmentation fault) raised in you program." I have been searching the internet for two days trying to see what I did wrong. What did I do wrong? Please help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

#include <iostream>
#include <iomanip>
#include <limits>
#include <string> 

using std::cout;
using std::cin;
using std::endl;
using std::fixed;
using std::setprecision;
using std:: showpos;


int main ()
{
    cout << "Welcome!" <<endl;
    cout << "\nThis is simple conversion program that will" <<endl;
    cout << "convert Fahrenheit temperature to Celsius temperature" <<endl<<endl<<endl;
    
    double fahren;
    do
        {
        cout << "Enter the Farenhiheit temperture: ";
        cin >> fahren;
        if (cin.fail ())
        {
            cin.clear();
            cin.ignore(999,'\n');            
            cout << "Invalid value, please enter a valid temperture";
            
        }
    } while (cin.fail());
        
    double celsius;
    celsius = (fahren -32) * 5.0/9.0;
    cout << fixed;
    cout << setprecision (2);
    cout <<showpos << fahren << " Degrees Fahrenheit = " << celsius << " Degrees Celsius " << endl << endl;

cout << endl<<endl;
system ("pause");
return 0;
}
Instead of making a do while, you should just use a while loop that checks for the cin.fail(), then within that while loop let the user re-enter their choice.
It should work after that!
Or change the if (cin.fail ()) to while (cin.fail ()) at line 26. Add another cin >> fahren; in there after the error message.

Then the original outer loop is unnecessary. I'm not sure how that originally could have worked anyway, since the cin.clear(); at line 28 ensures that the fail() condition could never be true at line 33. However when I tested the code, I did not get any crash or access violation - it simply output some default value of fahren and the celsius value, but ended cleanly.
That worked, I really appreciate the help on this. I was getting so frustrated. Thanks!!
Topic archived. No new replies allowed.