NoC*_*nde 11 c++ string stdstring string-literals equality-operator
string s;
bool b[] = {s=="", s==s.c_str(), s.c_str()==""};
Run Code Online (Sandbox Code Playgroud)
sets
b[] = {true, true, false};
Run Code Online (Sandbox Code Playgroud)
why is b[2] false?
If A==B and A==C, should that not imply B==C?
Vla*_*cow 14
In this expression
s.c_str()==""
Run Code Online (Sandbox Code Playgroud)
there are compared two pointers (addresses). The first one is the pointer returned by s.c_str() and the second one is the pointer to the first character (terminaring zero character) of the string literal "".
It is evident that the addresses are different (bear also in mind that the string literal has the static storage duration).
To get the expected result you should write instead
std::strcmp( s.c_str(), "" ) == 0
Run Code Online (Sandbox Code Playgroud)
至于这两个表达
s==""
Run Code Online (Sandbox Code Playgroud)
和
s==s.c_str()
Run Code Online (Sandbox Code Playgroud)
然后比较字符串,因为标准类std :: string的右操作数重载了运算符==。
| 归档时间: |
|
| 查看次数: |
157 次 |
| 最近记录: |