Nested Branches

Hey! Complete beginner here. Working on this lab for class. When I run the below code, it jumps to "I like animation too! Think of the endless possibilities!". Does anyone have ideas as to why it does that?

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

int main()
{
	string response1;
	string movies;
	string books;
	string responseA;
	string LiveAction = "Live-Action";
	string Animation;
	string responseB;
	string Fiction;
	string Nonfiction;

	cout << "Which do you prefer, movies or books? Enter either 'movies' or 'books': ";
	cin >> response1;
	if (response1 == movies) {
		cout << "Among possible types of movies (Live-Action, Animation), type your favourite: ";
		cin >> responseA;
	}
	if (responseA == LiveAction){
		cout << "Keepin' it real... I like it! \n" << endl;
	}
	 if (responseA == Animation){
		cout << "I like animation too! Think of the endless possibilities!" <<endl;
	}
	 else if (response1 == books){
		 cout << "Of the two possible types of books (Fiction, Nonfiction), type your favourite: ";
		 cin >> responseB;
	 }
	 if (responseB == Fiction){
		 cout << "Imagination makes for a good book!" << endl;
	 }
	 if (responseB == Nonfiction){
		 cout << "The truth can be fun!" << endl;
	 }

}
Well the issue is because of how you haven't initialized your variables to any particular values. And well the thing is that the default constructor of std::string creates an empty string, "". Now, following the program we see that it will check if response1 is equal to movies to which it won't because movies is an empty string. Then, it will check if responseA is equal to LiveAction, to which it won't because of how LiveAction contains the string "Live Action". From that point forward it will begin to execute the other if statements because of how you're comparing empty strings to empty string, which will result in true expression. Thus, we can see why it would execute the if statements. To fix simply assign the variables to some values or just compare it to string literals. Also, I believe you meant to nest some of those if statements.
Oh! I see. Thank you very much for your reply.
Last edited on
Topic archived. No new replies allowed.