Multiple IF statements in C++? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 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 ><

18th Jan 2018, 4:09 PM
Word Fisher
Word Fisher - avatar
6 Antworten
+ 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.
21st Jan 2018, 7:15 AM
Parker king
Parker king - avatar
+ 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.
18th Jan 2018, 4:59 PM
Jacob Pembleton
Jacob Pembleton - avatar
+ 1
Thank you for such a quick answer :) and with such good examples!!
18th Jan 2018, 4:41 PM
Word Fisher
Word Fisher - avatar
+ 1
https://code.sololearn.com/cij3bWfnnl67/?ref=app Here’s sort of what I was trying to do! Seems to be working now :)
18th Jan 2018, 4:52 PM
Word Fisher
Word Fisher - avatar
+ 1
@Martin oh thank you! Fun to learn something new ^_^
18th Jan 2018, 6:50 PM
Word Fisher
Word Fisher - avatar
0
@Parker king - ah I see! Thank you!
21st Jan 2018, 9:09 PM
Word Fisher
Word Fisher - avatar