我将一个参数传递给我的程序有一个问题,似乎不等于我作为参数放入的内容,除非它们是相同的.将它们变成一个字符串使它们相同,但我想知道为什么最初的二重奏不是.
这是我的代码:
int main(int argc, char *argv[]) {
if (argc>1) {
cout << "#" << argv[1] << "#" << endl;
cout << "#" << "nomast" << "#" << endl;
cout << (argv[1] == "nomast" ? "equal" : "not equal") << endl;
string s1 = argv[1];
string s2 = "nomast";
cout << (s1 == s2 ? "equal after all" : "nope") << endl;
system("pause");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我使用"call thingy.exe nomast"启动已编译的代码时,我得到了输出
#nomast#
#nomast#
not equal
equal after all
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)
我最好的想法是我没有正确处理"char*argv []".不知道如何以不同的方式处理它.
您正在比较其他字地址中的指针,而不是其内容.由于您使用的是C++,我建议您使用std::string并比较这些对象(就像您在第二次比较中所做的那样).
否则,如果必须处理C,只需使用strcmpC标准库中的函数.