本文介绍了比较两个char *是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的比赛条件不起作用!有人可以建议如何与C风格的字符串进行比较吗?

My match condition doesn't work! Can someone advise how to compare to C-style strings?

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;

即使 temp data 匹配,以下条件也不起作用:

Even though temp and data match, the following condition doesn't work:

if (stpr==data) {
  isData = true; 
}

不确定是否有帮助.从以下函数中调用 SaveData()函数:

Not sure if this helps. The SaveData() function is called from the function below:

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();
    }

}

推荐答案

由于 stpr data 都是C字符串,因此您需要使用 strcmp() :

Since both stpr and data are C strings, you need to use strcmp():

#include <string.h>
...
if (strcmp(stpr, data) == 0) {
    // strings are equal
    ...
} else {
    // strings are NOT equal
}

这篇关于比较两个char *是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:07