C++ “Expected Expression” Error

Question:
In my C++ repl I keep getting an error saying expected expression pointing to an else statement. Any help provided would be appreciated.
Code:


*Mysterious blurred code lol… (I’m just not revealing the project yet)

@HenryMiles3 Try putting a space in between “}” and “else” maybe?

1 Like

Still the same error. I haven’t seen this one before because I’m sure I’ve added all the necessary things.

@Strange indeed. Not sure either :confused:

The blur does not help I tried to rearrange the code in a manner that would make sense?

See if this helps:

#include <iostream>
using namespace std;

int main() {
    string function_command;
    cout << "example";
    cin >> function_command;

    while(function_command == "/function run system") {
        if(function_command == "/function run system") {
            cout << "example2";
        } else {
            cout << "another example";
        }
    }
    return 0;
}

Also, while and if are the same for what I got?

4 Likes

Thanks :smiley:

Yes that is what’s supposed to happen.

It fixes the else issue but then adds an issue where you type in the correct input and it doesn’t do anything. I think me originally trying to fix the if issue caused the else one. Basically if I want any if statement to work it won’t let me have a else statement and I don’t know why.

That’s because of the infinite loop.

You can either remove the loop or use “do-while”.

If you want to use the “do-while”, you can:

#include <iostream>
using namespace std;

int main() {
    string function_command;

    do {
        cout << "example: ";
        cin >> function_command;

        if(function_command == "/function run system") {
            cout << "example2" << endl;
        } else if (function_command != "/quit") {
            cout << "another example" << endl;
        }
    } while(function_command != "/quit");

    return 0;
}
2 Likes

That does fix the else error but in my original version the

Else if shouldn’t print out the examples unless told to. Is this something to do with the

Statement.

Hmmm… If you want the else to only print when you said so, you can control this through some other condition or command.
Like this:

#include <iostream>
using namespace std;

int main() {
    string function_command;

    cout << "example: ";
    cin >> function_command;

    if(function_command == "/function run system") {
        cout << "example2" << endl;
    } else if (function_command == "/function print else") {
        cout << "another example" << endl;
    }

    return 0;
}

But it’s really a shot in the dark I’m making here, I’m not sure what you are trying to achieve