In my code below, I want to be able to enter invalid ages for the first "if" over and over again and still get a prompt to enter an age, but so far if I enter an invalid age more than once, I get a "press any key to continue".
#include <iostream>
usingnamespace std;
int main()
{
int age;
cout << "Enter your age" << endl;
cin >> age;
if ((age <= 0) || (age > 110))
cout << "Please re-enter age. Your age cannot be less than or equal to zero or above 110. Those ages are invalid" << endl;
cin >> age;//re-entry of age if prompted
elseif (age < 21)
cout << "You cannot go drink at the bar." << endl;
elseif (age > 80)
cout << "You are too old to drink at the bar" << endl;
else
cout << "You are an age at which you can drink at the bar" << endl;//anyone eligible (ages 21 to 80)
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
int age;
cout << "Enter your age" << endl;
cin >> age;
if ((age <= 0) || (age > 110))
{
cout << "Please re-enter age. Your age cannot be less than or equal to zero OR above 110. Those ages are invalid" << endl;
cin >> age;//re-entry of age if prompted
}
elseif (age < 21)
{
cout << "You cannot go drink at the bar." << endl;
}
elseif (age > 80)
{
cout << "You are too old to drink at the bar" << endl;
}
else
{
cout << "You are an age at which you can drink at the bar" << endl;//anyone eligible (ages 21 to 80)
}
return 0;
}
For your code, if you enter an "invalid" age first, it will go into the first if-statement. This makes it execute that block, and none of the other "else [if]" blocks. It will skip through all the other else if/else statements and end the program.
Edit: If you only want the user to be able to re-enter a valid age once, change line 22 to just if instead of else if. Otherwise, do what Yay295 said and make it a while loop that will only stop once age > 0 && age < 110