c++stringcomparestring-literals

How to check if a string is equal to a string literal


I wanted to compare a string to a string literal; something like this:

if (string == "add")

Do I have to declare "add" as a string or is it possible to compare in a similar way?


Solution

  • In C++ the std::string class implements the comparison operators, so you can perform the comparison using == just as you would expect:

    if (string == "add") { ... }
    

    When used properly, operator overloading is an excellent C++ feature.