Checking string in if statement

Asked by At

Basically just trying to use == to check for a character

also im an idiot and i skipped a bunch of c++ classes and i have no idea how strings work as far as syntax goes, so any help there would be greatly appreciated

#include <string>

using namespace std;

int main(void)
{
    string letter;
    int number;

    letter = ' ';

    cout << "Please enter any ASCII letter" << endl;
    cin >> letter;


    if (letter == 'e')                       //Error is here
        {
            number = 1;
            cout << number << endl;
        }

    return 0;

}

I want to have the program check the letter and assign a number accordingly. I just made this simple script to test it, but I get error: no match for 'operator==' in 'letter == 'e''

2 Answers

1
galando On

Because 'e' is a char, not a string. You defined letter as a string, so you can do one of the following:

1) define letter as char.

2) keep it as a string, and change letter = ' '; to letter = " "; and if (letter == 'e') to if (letter == "e"). ("" represent a string, while '' represent a char).

1
mariotorres On

in C, a string is an array of characters. in C++, there is a standard library for it that extends the C definition.

in both C and C++, there is a difference between single and double quotes. 'd' means the character d and "d" means the string d. so this seems like an invalid type error. if you choose to use the std::string type, then you can get the first character by array indexing [0]. but i was wondering why you didn't just do something like

char letter = ' '