if/else with "or" operator

Sep 14, 2014 at 2:05am
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".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace 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

	else if (age < 21)
	
		cout << "You cannot go drink at the bar." << endl;
	

	else if (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;
	}
Sep 14, 2014 at 2:20am
You need to put your if and else statements inside brackets if they are more than one line.

(You can be too old to drink at the bar?)
Last edited on Sep 14, 2014 at 2:24am
Sep 15, 2014 at 10:28pm
Thanks! I applied the brackets but I'm still getting the same issue...it's probably to do with the placement of the brackets right now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

#include <iostream>
using namespace 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

}

	else if (age < 21)

{

	cout << "You cannot go drink at the bar." << endl;

}

	else if (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;
}
Sep 15, 2014 at 10:34pm
Change the first if to a while, and the else..if after it to just an if.
Sep 15, 2014 at 10:37pm
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
Last edited on Sep 15, 2014 at 10:47pm
Sep 20, 2014 at 2:56am
Thank you! Figured it out.
Topic archived. No new replies allowed.