字符串字面量之间的比较
-
20-09-2019 - |
题
此非常简单的代码:
#include <iostream>
using namespace std;
void exec(char* option)
{
cout << "option is " << option << endl;
if (option == "foo")
cout << "option foo";
else if (option == "bar")
cout << "opzion bar";
else
cout << "???";
cout << endl;
}
int main()
{
char opt[] = "foo";
exec(opt);
return 0;
}
产生两个警告:在未指定的行为字面字符串比较
你能解释为什么正是这个代码不工作,但如果我更改
char opt[]
到
char *opt
它的工作原理,但生成警告?这是否与该\ 0终结?两者有什么声明选择的区别?如果我用const修饰?的解决方案是使用的std :: string?
解决方案
字符数组或字符指针是不是真的同样的事情在C ++中的字符串的类对象,所以这
if (option == "foo")
不比较字符串option
到字符串“foo”的它与字符串“foo”的的地址进行比较option
的地址。您需要使用的许多字符串比较功能之一,如果你想知道如果选项是一样的“富”。 strcmp
是这样做的明显的方式,也可以使用std::string
代替char*
其他提示
您可以使用==
符来比较字符串只有在使用std::string
(这是一个很好的做法)。如果使用C语言风格的char * /焦炭[]字符串,则需要使用C函数strcmp
或strncmp
。
您还可以使用std::string::operator ==
与C要比较的字符串std::string
:
std string foo = "foo";
const char *bar = "bar";
if (foo == bar)
...
为什么它不工作的原因是因为比较不比较字符串,但字符指针。
它之所以可以:当您使用字符工作*是因为编译器可以决定存储文本字符串“选择”一次,重复使用两个引用(我相信我已经看到了编译器设置的地方,表示编译器是否执行此)。
在炭选择[]的情况下,编译器的副本字符串文字为选择阵列保留(可能在堆栈上)的存储区域,这会导致指针是不同的。
Renze
看起来你从Java / C#来到:)在C ++中的字符串只是一个指针,其中字符被存储的存储器,并在端部零炭。如果字符串“看”等于他们可能会指向不同的区域在内存中,将不相等。检查平等要么使用C ++的类的std :: string或C函数strcmp。
有关C ++我会使用的std :: string 溶液:
#include <iostream>
#include <string>
using namespace std;
void exec(string option)
{
cout << "option is " << option << endl;
if (option == "foo")
cout << "option foo";
else if (option == "bar")
cout << "option bar";
else
cout << "???";
cout << endl;
}
int main()
{
string opt = "foo";
exec(opt);
exec("bar");
char array[] = "other";
exec(array);
return 0;
}
的std :: string知道如何创建自己出的char [],字符*等,所以你仍然可以调用这些方法的功能了。