0

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.

1
  • I saw that post and I thought that they should be equal. eeroika answer is right. compare return an int and I thought it was a bool. The difference is in the casting Commented Sep 15, 2021 at 14:04

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.