+ 1
Multiple IF statements in C++?
Hi! How can I use multiple if statements in C++? I want to have each case == to a string. When I did that all my statements occurred. I tried with switch instead, but the code refused to work when the different cases were equal to “words”. Ah I am still pretty new to this, so all help is appreciated! :) Hope my explanations make sense ><
6 Respostas
+ 3
Like Martin pointed out, for your code you want to start with an if statement then follow it with else if, then end with else. In the code he puts it will first check to see if y is equal (more accurate to say equivalent) to car. If not it will check if y = aeroplane, if not it will check for spaceship, then if none of those conditions are met it will print “try again”. Whereas if you do just if statements, each if statement is treated as separated situations. This is why to program you put will print two things unless the input is spaceship because the else is what links to a previous statement.
+ 2
int a = 0;
if (a == 1) cout << “5”;
else if (a == 0) cout << “fhhh”;
else cout << “nope”;
Outputs fhhh because a is not 1, but it is 0.
+ 1
Thank you for such a quick answer :) and with such good examples!!
+ 1
https://code.sololearn.com/cij3bWfnnl67/?ref=app
Here’s sort of what I was trying to do! Seems to be working now :)
+ 1
@Martin oh thank you!
Fun to learn something new ^_^
0
@Parker king - ah I see! Thank you!