Search code examples
c++stringcharstrcmp

Using strcmp on a vector


I have a vector of strings and I want to compare the first element of the vector with a bunch of different "strings".

Here is what i wanted to do:

if (strcmp(myString[0], 'a') == 0)

but strcmp doesnt work. I basically want to check the contents of myString[0] with a bunch of different characters to see if there is a match. So it would be something like

if (strcmp(myString[0], 'a') == 0){
}
else if (strcmp(myString[0], 'ah') == 0){
}
else ifif (strcmp(myString[0], 'xyz') == 0)

etc..

What can i use to do this comparison? Compiler complains about "no suitable conversion from std:string to "constant char*" exists so i know it doesnt like that im doing a string to char comparison, but i cant figure out how to correctly do this.


Solution

  • std::string overloads operator== to do a string comparison, so the equivalent to

    if (strcmp(cString, "other string") == 0)
    

    is

    if (cppString == "other string")
    

    So your code becomes (for example)

    else if (myString[0] == "ah")