alin
alin

Reputation: 45

C++ operator '==' cannot compare string[i] with another string. Compile error

#include <iostream>
using namespace std;

int main()
{
    string str = "abcdef";
    string x = "a";
    if (str[0] == x) {
        //do something...
    }
    return 0;
}

and cannot compile.

"error: no match for ‘operator==’ (operand types are ‘__gnu_cxx::__alloc_traits, char>::value_type’ {aka ‘char’} and ‘std::string’ {aka ‘std::__cxx11::basic_string’})"

Upvotes: 0

Views: 648

Answers (3)

Francis Cugler
Francis Cugler

Reputation: 7905

You are asking why your code doesn't compile.

If we look at your code line by line we can see that...

string str = "abcdef";
string x = "a";
if (str[0] == x)

From line one above you declared a string str that stores the set of character encoding values of {a, b, c, d, e, f} either it be ASCII, UTF-X, etc.

On your second line you declare another string x that stores the set of character encoding values of {a} either it be ASCII, UTF-X, etc.

The problem of not compiling does not show up until the expression within the if statement.

The LHS of the expression you are using std::string's operator[] to access the value at the index of its first location in memory. This returns a reference to a character at that indexed location. Then on the RHS of the expression you are comparing the LHS character reference against the std::string named x.

The issue here is that there is no conversion between a reference to a char and std::string and that you have not defined your own operator==() that would do so.

The easiest fix is to change either the LHS to a string or the RHS to a char. There may also be available functions or algorithms within the STL that would do the comparison(s) for you. You can do an online search for that.

You can refer to cppreference:string:basic_string:operator_at for detailed information about std::string's operator[]. And you can search their site for other functions, algorithms and string manipulators and other types of containers. It is probably one of the best resources out there for the C/C++ STL.

Upvotes: 0

Andre Gamez
Andre Gamez

Reputation: 33

The problem here is that you're comparing a char with a string

str[0] is actually a char

Just need to declare x as char...

#include <iostream>
using namespace std;

int main()
{
    string str = "abcdef";
    char x = 'a';
    if (str[0] == x) {
        //do something...
    }
    return 0;
}

Upvotes: 2

Slava
Slava

Reputation: 44238

std::string except for being a string also provides interface of being a container of chars. So when you use operator[] you access and individual char from this container and you cannot compare a char with a string. If you want to have a single symbol string instead use std::string::substr() with length 1. Or if you want the symbol to compare with another one declare x as being a single char instead of string.

Upvotes: 4

Related Questions