Question about if statements

I have searched around and I am apparently not searching for the right thing. My question is, can you put an if statement within an if statement?

For example...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if(userInput == 2)
{
 cout << "Random question";
 cin >> "Answer to random question";
 
 if(Answer to random question == 1)
 {
  yadda yadda
 }
 else()
 {
 more yadda yadda
 }
}


When I compile, it doesn't seem to run the second if statement, the program just exits. So I am assuming that you are not able too, although I might just be missing something.
You can definitely nest if statements. The only reason the second one wouldn't run is if userInput != 2. Also, for your else, you don't use ().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
std::cout << "Choose 2 for a question\n";
std::cin >> choice;

if(choice == 2) {
	std::cout << "You chose 2!\n";
	std::cout << "What is 2 + 2?";
	std::cin >> answer;
	if(answer == 4) {
		std::cout << "Correct!";
	} else if(answer == 3) {
		std::cout << "3 is close but the answer was 4!";
	} else {
		//etc..
	}
} else {
	std::cout << "You didn't choose 2, exiting program.";
}

return 0;
Last edited on
Topic archived. No new replies allowed.