I need help with my program.

I'm very new to C++ and I don't understand what's wrong with my code. If the age is less than 18 or greater than 99, it should just quit the "game", but it continues to ask what the name of the player is, can someone help me please?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class IntroductionToGame{
public:

//VARIABLES//

int age;

//WELCOMING PLAYER//

int welcomeToTheGame(){
cout << "Hello Player, welcome to the game!" << endl;
cout << "Please, enter your age." << endl;
cin >> age;

//TESTING TO SEE IF PLAYER IS OLD ENOUGH//

try{
if (age <= 17 || age >= 100)
throw 101;
}catch (int age){
cout << "TOO YOUNG TO PLAY. " << endl;
cout << "CTRL + Z to quit." << endl;
}

//CONFIRMING AGE IS VALID//

if(age >= 18 && age <= 99){
cout << age << "? Great! You seem to be old enough to play, let's continue." << endl;
}else if(age < 18 && age > 99){
return -1;
}

if(age <=17 || age >= 100){
string name;

cout << "What is your first name?" << endl;
cin >> name;
}
}

};

int main(){

IntroductionToGame introGame;
introGame.welcomeToTheGame();

}
If the age is less than 18 or greater than 99
if(age < 18 && age > 99)

There is a difference between AND and OR.


However, this occurs on an else-branch. When do you get to that else?
When the condition in the if is false.
When age >= 18 && age <= 99 is false.

Is there a case, when age is not between 18 and 99, but is not below 18 nor above 99?

In other words, do you need to test anything at all in that else-branch?
OH, I see what I did wrong, thank you for that. I'll see if I can go update the code real quick.
In your IF statements, you had if (age < 18 && age > 99)
I suggest you do
if((age < 18) || (age > 99))
&& means and, and || means or if you want it to be less than 18 or greater than 99 then || is it but you want it to be less than 18 and greater than 99 then you do &&


What I always do is have a variable that you send into your function called status or something. And the function change the value of status to something like 1 or -1, return status; then have
1
2
3
4
5
if (status == 1) {
// Your leave command here
} else {
// Your function to continue here
}

You can also use the not operator !=
Last edited on
Topic archived. No new replies allowed.