In the following code, I was trying to create a function in a public space of class "SOMECLASS" that would take the user input consisting of float values (declared in a private space of the same class) and verify the user input. If the entered value is not a float, then it will display an error message and the user will be given an opportunity to re-enter this value. However, once some garbage is entered, the loop runs from the very beginning, making the user enter all those values again.
PS: I know that multiple loops can be created to check each value separately and break the loop if the statement is correct but I want to know if there are any easier ways to do this.
Thank's in advance for help.
void SOMECLASS::USER_INPUT() {
bool loopBool = true; // it is used to manage the do/while loop below;
do { // the loop is going to run for as long as the boolean is true;
cout << " Enter the frequency of the cumputer's CPU in GHz: ";
cin >> float1;
if (!float1) { // checks if the value entered is valid;
cin.clear();
cin.ignore (numeric_limits<streamsize>::max(), '\n');
cout << "INVALID INPUT!!!" << endl << endl;
}
else {
cout << " Enter the Hard Drive Capacity in TB: ";
cin >> float2;
if (!float2) { // checks if the value entered is valid;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "INVALID INPUT" << endl << endl;
}
else {
cout << " Enter the capacity of your RAM in GB: ";
cin >> float3;
if (!float3) { // checks if the value entered is valid;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "INVALID INPUT" << endl << endl;
}
loopBool = false;
}
}
} while (loopBool);
};
OUTPUT:
Computer #1/2
|--> Enter the frequency of the cumputer's CPU in GHz: 2.3
|--> Enter the Hard Drive Capacity in TB: 4
|--> Enter the capacity of your RAM in GB: asd
INVALID INPUT
`--> The final cost is: ...
DESIRED OUTPUT:
Computer #1/2
|--> Enter the frequency of the cumputer's CPU in GHz: 2.3
|--> Enter the Hard Drive Capacity in TB: 4
|--> Enter the capacity of your RAM in GB: asd
INVALID INPUT
|--> Enter the capacity of your RAM in GB: 16
`--> The final cost is: ...
If it's mandatory for the number to be float(decimals) then can you do:- Ceil(number)<>floor(number)
If it's an integer value then floor and ceil will be equal.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.