Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two char* for equality [duplicate]

Tags:

c++

c-strings

Possible Duplicate:
What is the proper function for comparing two C-style strings?

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;

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

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

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

}
like image 864
Bryan Wong Avatar asked Nov 25 '12 07:11

Bryan Wong


2 Answers

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
}
like image 88
NPE Avatar answered Sep 30 '22 08:09

NPE


This condition wont work because the == operator is not overloaded for 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.

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.

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.

like image 28
Coding Mash Avatar answered Sep 30 '22 08:09

Coding Mash