I need help with this If or Else Program.

Hey Everybody :)

If i change strings a1 and a2 to contain "\n" as in:
 
string a1 = "Stoop\n" , a2 = "JAAAH!\n" ;

Than the "else" statement whill be run in every scenario and my question is why?
i am not intrested in another way of achieving a new line. I am simply curiouse as to why the program chooses to run the "else" statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  using namespace std;

int main() {
    string a1 = "Stoop" , a2 = "JAAAH!" ;
    int x;
f:
    cout << "Hello This is a test Enter a number between 1-2\n";
    cin >> x;
    if ( x == 1 ){
    cout <<a1<<"\n";}
     if ( x == 2 ){
     cout <<a2<< "\n";}
      else
      cout<<"Try again Scrub\n";
      goto f;
}


Thanks in advance to anyone kind enough to offer some insight :)
Last edited on
Line 11 should be else if( x == 2)

Here's basically what is happening in your current program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;

int main() {
	string a1 = "Stoop\n", a2 = "JAAAH!\n";
	int x;
f:
	cout << "Hello This is a test Enter a number between 1-2\n";
	cin >> x;
	if(x == 1){ // Checks to see if x is equivalent to 1.
		cout << a1 << "\n"; // This executes if the above evaluates to true. 
	}
	if(x == 2){ // Checks to see if x is equivalent to 2.
		cout << a2 << "\n"; // This executes if the above is true.
	}
	else // Executes this block of code if x == 2 evaluates to false.
		cout << "Try again Scrub\n";
	goto f;
}


What's happening is if you enter '1' then it checks if x == 1. Ok it does. So now it checks if x == 2. Nope. Finally since it does not == 2 it goes to the else block. When you use if back to back like you are they get evaluated independently of eachother. When you use if/else if/else if either the if or else if evaluates to true, it executes whatever is in that block of code and then breaks out of the entire if-else if-else chain.

Hope I made this clear enough.
Last edited on
Alright so from what i gather anytime there are multiple "if" statements "if else" should be applied or i am completely of?

Also thank you for the swift response.
Last edited on
That is correct, but only if you want all the 'if' statements to lead to one default fallback option.

On a side note, 'goto' is generally frowned upon (its hard to see whats going on), try using a loop instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//...
int main() {
    string a1 = "Stoop\n", a2 = "JAAAH!\n";
    int x;

    while (true) { // infinite loop
        cout << "Hello! This is a test! Enter a number between 1 and 2: ";
        cin >> x;
    
        if (x == 1) {
            cout << a1 << "\n";
            break;  // escape from the loop
        } else if (x == 2) {
            cout << a2 << "\n";
            break;  // escape from the loop
        } else {
            cout << "Try again!";
        }
    }
}
Topic archived. No new replies allowed.