Ask coding questions

← Back to all posts
How to use C++ else if statement?
bwoop (112)

I just started c++ and my else if statement isn't working. Can someone help?

Answered by InvisibleOne (2687) [earned 5 cycles]
View Answer
InvisibleOne (2687)

You are doing your else if statements incorrectly. They should look like this:

#include <iostream>
using namespace std;

int main() {
   char name[50];
   cout << "Please enter your name: ";
   cin >> name;
	 if (name == "loser") {
		 cout << "Why is your name loser?";
	 } else if (name == "haha") {
		 cout << "You seem happy";
	 } else {
		 cout << "Your name is boring";

They don't start on a new line

bwoop (112)

@InvisibleOne Thanks! That's how i had it the first time, and it wasn't working. Could you also tell me why it is still saying "great" even if the answer is wrong?

m4rus3ru (15)


if( (i = sum) ){

should be

if(i == sum){

You where assigning the value of sum to i.
For comparing you use the == operator, for assigning the = operator.
Using the = operator in an if statement will return true or false based on if the assigning of the value was successful.

InvisibleOne (2687)

You should use to double equal sign instead of a single == @bwoop