I am getting different results when using ==
or std::string::compare
between two strings.
This is the code I am executing.
#include <iostream>
#include <string>
int main()
{
std::string str1 = "W";
char tmpChar = 'W';
std::string str2(1, tmpChar);
bool equalCompare = str1.compare(str2);
bool equalSign = (str1 == str2);
std::cout << "Compare result: " << equalCompare << std::endl;
std::cout << "Equal sign result: " << equalSign << std::endl;
return 0;
}
I guess it has to do with how I am creating str2
, but that is the way I found out to convert a single char to a string.
CodePudding user response:
Differences between compare and == for std::string
The difference is in what they return. ==
returns true when the strings compare equal and false otherwise. compare
returns negative integer when *this
is before the argument, zero when strings are equal, and positive integer when the argument is before *this
.