Unable to create else if statement for switch assignment

Course link:
https://www.codecademy.com/courses/learn-c-plus-plus/lessons/cpp-conditionals-and-logic/exercises/review

I believe this exercise is wanting me to right a switch code but I was wondering if I could do it as an else if as well. Everything was going going and I could compile and run it, until I put the else statement in:

#include

int main() {

double eweight;
int planet;

std::cout << ("please enter your current Earth weight: ");
std::cin >> eweight;

std::cout << (“1. Mercury\n2. Venus\n3. Mars\n4. Jupiter\n5. Saturn\n6. Uranus\n7. Neptune\n”);

std::cout << ("Please select Planet by listed number: ");
std::cin >> planet;

if (planet == 1) {

double mweight;

mweight = (eweight * 0.38);
std::cout << ("Target weight for Mercury is ") << mweight << “\n”;

}

else if (planet == 2) {

double vweight;

vweight = (eweight * 0.91);
std::cout << ("Target weight for Venus is ") << vweight << “\n”;

}

else if (planet == 3) {

double maweight;

maweight = (eweight * 0.38);
std::cout << ("Target weight for Mars is ") << maweight << “\n”;

}

else if (planet == 4) {

double jweight;

jweight = (eweight * 2.34);
std::cout << ("Target weight for Jupiter is ") << jweight << “\n”;

}

else if (planet == 5) {

double sweight;

sweight = (eweight * 1.06);
std::cout << ("Target weight for Saturn is ") << sweight << “\n”;

}

else if (planet == 6) {

double uweight;

uweight = (eweight * 0.92);
std::cout << ("Target weight for Uranus is ") << uweight << “\n”;

}

else if (planet == 7); {

double nweight;

nweight = (eweight * 1.19);
std::cout << ("Target weight for Neptune is ") << nweight << “\n”;

}

else {

std::cout << “Please retry and be sure to select a planet from 1 to 7\n”;
}

}

This is the error I get when attempting to compile:

$ g++ space.cpp
space.cpp: In function ‘int main()’:
space.cpp:79:1: error: ‘else’ without a previous ‘if’
else {
^~~~

If I comment out the else statement, it will compile and run.

Any advice?

Hi,
Your error suggests a disconnect between the else statement and the previous statements in the chain. As the else looks ok, you might want to cast your eye over the previous one in the chain.

else if (planet == 7); ← you’ve an errant semi-colon

I’m not 100% on c++, but I believe that’s your issue.

Hope that helps

1 Like

You need a char input variable for cin and then convert that to an integer for your if statements using atoi function.