C++ 字符串和文本之间的比较
下面是非常简单的代码:C++ 字符串和文本之间的比较,c++,string,comparison,warnings,literals,C++,String,Comparison,Warnings,Literals,下面是非常简单的代码: #include <iostream> using namespace std; void exec(char* option) { cout << "option is " << option << endl; if (option == "foo") cout << "option foo"; else if (option == "bar") co
#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;
}
到
它可以工作,但会生成警告?是否与\0终止相关?这两种选择声明之间有什么区别?如果我使用常量限定符呢?解决方案是使用std::string?只有在使用
std::string
时,才可以使用=
运算符比较字符串(这是一种很好的做法)。如果使用C风格的char*/char[]字符串,则需要使用C函数strcmp
或strncmp
您还可以使用std::string::operator==
将std::string
与C字符串进行比较:
std string foo = "foo";
const char *bar = "bar";
if (foo == bar)
...
char数组或char指针与C++中的String类对象并不完全相同,因此这个
if (option == "foo")
不将字符串
选项
与字符串文字“foo”进行比较,而是将选项
的地址与字符串文字“foo”的地址进行比较。如果您想知道该选项是否与“foo”相同,则需要使用多个字符串比较函数之一strcmp
是实现这一点的明显方法,或者您可以使用std::string
而不是char*
它不起作用的原因是比较不是比较字符串,而是比较字符指针
使用char*时,可能起作用的原因是编译器可能决定存储文本字符串“opt”一次,并将其用于两个引用(我确信我在某些地方看到了编译器设置,指示编译器是否执行此操作)
对于char opt[],编译器将字符串文本复制到为opt数组保留的存储区域(可能在堆栈上),这会导致指针不同
Renze
< P> C++中,我将使用STD::String:#包括
#包括
使用名称空间std;
void exec(字符串选项)
{
当然可以,但是如果我不想使用C includes并使用char*作为函数的参数,那么如果(std::string(option)==std::string(“foo”))?如果(std::string(option)==foo)这样做好吗“我想,我已经编辑了这个答案。”WISO:为什么你想用char而不是字符串来工作,但不包括cstring函数?你是对的。一般来说,我不喜欢在C++中使用C库,所以我将切换到STD::String。我想在参数中使用char *来改变函数的签名。如果执行'if(option==“foo”)`,则不比较两个字符串--比较两个指针它“起作用”不是因为您将其声明为char*,而是因为您将其分配给指向字符串文本“foo”。然后,当您稍后将其与文本“foo”进行比较时,如果编译器将这两个“foo”组合在一起,则地址将是相同的s编译器通常会识别出您在两个位置使用了相同的字符串文字,并让它们都引用相同的文字,但这在一般情况下是行不通的。如果John comment中不够清楚,char x[]=“…”
在内存中创建一个连续的字符块
并复制内容,而char*x=“…”
创建一个指针并分配文本的地址。
std string foo = "foo";
const char *bar = "bar";
if (foo == bar)
...
if (option == "foo")
#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;
}