C++: Help with cin difference between Linux and Windows
- by Krashman5k
I have a Win32 console program that I wrote and it works fine. The program takes input from the user and performs some calculations and displays the output - standard stuff. For fun, I am trying to get the program to work on my Fedora box but I am running into an issue with clearing cin when the user inputs something that does not match my variable type. Here is the code in question:
void CParameter::setPrincipal() {
double principal = 0.0;
cout << endl << "Please enter the loan principal: ";
cin >> principal;
while(principal <= 0)
{
if (cin.fail())
{
cin.clear();
cin.ignore(INT_MAX, '\n');
}
else
{
cout << endl << "Plese enter a number greater than zero. Please try again." << endl;
cin >> principal;
}
}
m_Parameter = principal;
}
This code works in Windows. For example, if the user tries to enter a char data type (versus double) then the program informs the user of the error, resets cin, and allows the user another opportunity to enter a valid value.
When I move this code to Fedora, it compiles fine. When I run the program and enter an invalid data type, the while loop never breaks to allow the user to change the input.
My questions are; how do I clear cin when invalid data is inputted in the Fedora environment? Also, how should I write this code so it will work in both environments (Windows & Linux)?
Thanks in advance for your help!