I came across a very simple but confusing problem today.
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "123";
string a = "1";
string b = "1";
cout << ((str[0]+"") == a) << endl;
cout << (a==str.substr(0,1)) << endl;
cout << (a==b) << endl;
}
The output is: 0 1 1
Why the first compare statement is false? How does c++ compare two string when using == operator?
str[0]+"" is something rather odd - you take the numeric value of the first character (which is 49, assuming an ASCII encoding of the character '1'), and add it to a pointer to the start of an empty string. This gives you an invalid pointer, and undefined behaviour.
If you wanted to make a string out of the first character, that would be one of
string(1, str[0])
string(str, 0, 1)
str.substr(0, 1)
string() + str[0]
which would compare equal to a
They are different types,the result of the expression str[0]+"" is char * type(""is char * not string,for char * the operator + is not overloaded,so its behavior is undefined), but a is string type, obviously they are not equal.To see reason,you can run this code:
cout<<typeid(str[0]+"").name()<<endl;
cout<<typeid(a).name()<<endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With