Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;使用==?比较两个字符串?_C++_String - Fatal编程技术网

C++ c++;使用==?比较两个字符串?

C++ c++;使用==?比较两个字符串?,c++,string,C++,String,今天我遇到了一个非常简单但令人困惑的问题 #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.su

今天我遇到了一个非常简单但令人困惑的问题

#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;

}
#包括
#包括
使用名称空间std;
int main(){
字符串str=“123”;
字符串a=“1”;
字符串b=“1”;
cout
str[0]+“
有些奇怪-您获取第一个字符的数值(即49,假设字符
'1'
采用ASCII编码),然后将其添加到指向空字符串开头的指针中。这会给您一个无效指针和未定义的行为

如果您想从第一个字符生成一个字符串,那么这将是

string(1, str[0])
string(str, 0, 1)
str.substr(0, 1)
string() + str[0]

它们是不同的类型,表达式
str[0]+'
的结果是
char*
类型(
char*
不是
string
,对于
char*
运算符
+
没有重载,因此其行为是未定义的),但
a
string
类型,显然它们不相等。要查看原因,可以运行以下代码:

cout<<typeid(str[0]+"").name()<<endl;
cout<<typeid(a).name()<<endl;

coutpossible duplicate of What do you think's type of str[0]?@DeepBlackDwarf即使标题几乎相同,我也不会称之为duplicate。这里的问题根源是用字符索引字符串。谢谢!我忘了在使用+组合两个字符串时,至少有一个操作数必须是字符串类型。
str[0]+''
违反了这条规则。我不知道你指的是哪一条?
str[0]+''
。它是
char+char const[0]
。如果参数的顺序不同,那么我会理解
char*
的结果。但事实上,我认为结果应该是
char
。我不确定。它是
char*
,您可以使用我答案中的代码来测试它。