Make loop continue inspite of invalid input
Hi,
Basically what I want is for the loop to continue asking the user for the Number, minutes, and seconds and to continue summing the minutes and seconds while discarding any invalid user input (which in this case would be negative numbers) and print out an error message . 0 is the sentinel value.
What i currently have is that when an invalid (<0) value is inserted for Number, and/or minutes, and/or seconds---the main fx calls a void function and exits (return 1)...
Thanks!
The following is my code:
--------------------------
cout << "Enter thenumber:" << endl;
cin >> Number;
while (Number<0)
{
IsDataValid_Echo(Number, minutes, seconds);
return 1; //Function call with 3 arguments
}
sum = 0;
sums = 0;
count = 1;
while (Number!=0 && seconds>0 && minutes>0)
{
cout << "Enter the number of minutes:" << endl;
cin >> minutes;
sum = sum + minutes;
cout << "Enter the number of seconds:" << endl;
cin >> seconds;
sums = sums + seconds;
while (minutes<0 || seconds<0)
{
IsDataValid_Echo(Number, minutes, seconds);
return 1;
}
cout << " number " << Number << ", " << minutes << " and " << seconds << endl;
cout << "Total time is " << sum << " minutes " << " and " << sums << " seconds." << endl;
cout << "For the next value," << endl;
cout << "Enter the number:" << endl;
cin >> Number;
count ++;
}
Re: Make loop continue inspite of invalid input
If you want to validate input in a loop, you typically use something like this:
Code:
do
{
get input;
if (input is invalid)
print error message;
} while (input is invalid);
If you don't like the fact that you have to repeat the expression that checks whether the input is valid, you could do something like this:
Code:
bool bFinished = false;
do
{
get input;
if (input is invalid)
print error message;
else
bFinished = true;
} while (!bFinished);
And if you don't want to use a variable to keep track of the state of your operation, you could do this:
Code:
while (true)
{
get input;
if (input is valid)
break;
print error message;
}
I generally prefer a formulation that doesn't use break, but it's up to you.