thejdah thejdah - 2 months ago 6
C++ Question

error when calling char to allow user to enter choice

I am writing a simple text game in C++. The user has the option of choosing the left room or the right room. I did have this set up as an int statement: enter 1 for left, enter 2 for right. Now I would like to have the user enter left for left room, right for right room.

I replaced the int with char, but I am getting an error.

#include <iostream>

using namespace std;

int main() {

char decision;
cin >> decision;

if (decision == left) {
cout << "went left" << endl;
}

return 0;
}



Error: comparison between pointer and integer

Answer
  1. char stands for a single character - what you need is a string (multiple characters).

  2. when you actually have the user's value in decision you need to compare it to the string "left" rather than just left which the compiler tries to interpret as a symbol (like a variable name).

All in all:

#include <iostream>
#include <string>

using namespace std;

int main() {

    string decision;
    cin >> decision;

    if (decision == "left") {
        cout << "went left" << endl;
    }

    return 0;
}
Comments