Hi, I've only just recent began learning C++ and am having a little issue with while loops when the condition for the while loop is an input, of type double, from the user. I understand that if the user doesn't enter a value compatible with the double type then the loop is automatically broken. The issue is my console application exits upon entering anything other than a double.
The current exercise I'm working on has asked to make use of a while loop and if statements to calculate a number of entered measurements and output the total. The user enters a value and then the measuring system (i.e 25 m for 25 metres). It also has to record and output the highest and lowest values entered.
double value = 0;
double total = 0;
double high = 0;
double low = 0;
string unit = " ";
while (cin >> value >> unit && unit != "convert")
{
if (unit == "in") {total = total+(value*2.54);// in = inches converting to cm
if (value*2.54 > high) high = value;
if (value*2.54 < low) low = value;
}
else if (unit == "m"){total = total+(value*100);// m = metres, converting to cm
if (value*100 > high) high = value;
if (value*100 < low) low = value;
}
else if (unit == "ft"){total = total+(value*30.48);// ft = feet, converting to ft
if (value*30.48 > high) high = value;
if (value*30.48 < low) low = value;
}
else if (unit == "cm"){total = total+value;// cm = centremetres
if (value*2.54 > high) high = value;
if (value*2.54 < low) low = value;
}
else cout << "Unable to calculate unit type - " << unit << endl;
value = 0;
}
cout << "Total length in centre-metres: " << total << endl
<< "Total length in metres: " << total/100 << endl
<< "Total length in feet: " << total/30.48 << endl
<< "Total length in inches: " << total/2.54 << endl
<< "\nHighest value: " << high << ", Lowest value: " << low << endl;
keep_window_open();
return 0;
keep_window_open() is part of the custom header file that came with my C++ book, all it does is ask for a user to enter a character to quit.
I know the current state of the program is a bit bloated but I wanted to get it all working correctly first. I had to use a work around of, if the user enters 'convert' as a unit the loop is killed so I could actually see if it was working correctly. The program does finish/complete its task when anything other than an double is entered into value but the results flash up on the console window and then it exits immediately.
Any help is appreciated.