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
usingnamespace 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 :)
#include <iostream>
#include <string>
usingnamespace 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/elseif/else if either the if or elseif evaluates to true, it executes whatever is in that block of code and then breaks out of the entire if-else if-else chain.
//...
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
} elseif (x == 2) {
cout << a2 << "\n";
break; // escape from the loop
} else {
cout << "Try again!";
}
}
}