C++ 比较两个 char* 是否相等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13549299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing two char* for equality
提问by Bryan Wong
Possible Duplicate:
What is the proper function for comparing two C-style strings?
可能的重复:
比较两个 C 样式字符串的正确函数是什么?
My match condition doesn't work! Can someone advise how to compare to C-style strings?
我的匹配条件不起作用!有人可以建议如何与 C 风格的字符串进行比较吗?
void saveData(string line, char* data){
char *testString = new char[800];
char *stpr;
int i=0;
bool isData=false;
char *com = data;
strcpy(testString,line.c_str());
stpr = strtok(testString, ",");
while (stpr != NULL) {
string temp = stpr;
cout << temp << " ===== " << data << endl;
Even though temp
and data
match, the following condition doesn't work:
即使temp
和data
匹配,以下条件也不起作用:
if (stpr==data) {
isData = true;
}
Not sure if this helps. The SaveData()
function is called from the function below:
不确定这是否有帮助。该SaveData()
函数是从下面的函数调用的:
void readFile(char* str){
string c="", line, fileName="result.txt", data(str);
ifstream inFile;
inFile.open(fileName.c_str());
resultlist.clear();
if(inFile.good()){
while(!inFile.eof()){
getline(inFile, line);
if(line.find(data)!=string::npos){
cout << line << endl;
}
saveData(line, str);
}
inFile.close();
}
}
回答by NPE
回答by Coding Mash
This condition wont work because the ==
operator is not overloaded for char*
.
此条件不起作用,因为==
运算符没有为 重载char*
。
if(stpr==data)
{
isData = true;
}
Use this instead.
改用这个。
if (strcmp(stpr, data) == 0)
{
isData = true ;
}
strcmp()
returns 0
if both the cstrings are equal. Make sure that both the cstrings you are matching hold some legal memory and are null terminated at the end.
strcmp()
0
如果两个 cstring 相等,则返回。确保您匹配的两个 cstring 都保存了一些合法内存,并且在末尾以 null 结尾。
Edit:
编辑:
To avoid any sort of hassle and bugs, it is advisable not to use raw char*
and use std::string
instead. So better make them strings and compare them.
为避免任何麻烦和错误,建议不要使用 raw而是char*
使用std::string
。所以最好把它们做成字符串并比较它们。
std::string data ; //passed or declared as string
std::string stpr ;
.....
//Do some work.
if (stpr == data)
//do work here
This approach would save you a lot of troubles.
这种方法可以为您省去很多麻烦。
回答by Rahul Tripathi
You are trying to compare two char*. YOu can try using strcmp(stpr, data)
for checking the conditions.
您正在尝试比较两个 char*。您可以尝试使用strcmp(stpr, data)
来检查条件。
Better use it like
更好地使用它
if(strcmp(stpr, data)==0){..}