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();
}
}
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With