c++ - string compare failing after reading line from txt file -


i trying read file line line , compare string in code. somehow following code not giving expected result. not follow missing during comparison:

code

int main(int argc, char** argv) {     std::string filepath="e:\\data\\stopfile.txt";     std::string line;     std::ifstream myfile;     std::string test="ball";     myfile.open(filepath.c_str());     if(myfile.is_open()){         while(getline(myfile,line)){             std::cout<<line<<std::endl;             if(!line.compare(test)){                 std::cout<<"success"<<std::endl;             }             else{                 std::cout<<"fail"<<std::endl;             }         }     }     myfile.close();      if(!test.compare("ball")){         std::cout<<"success"<<std::endl;     } } 

output

apple fail ball fail cat fail success 

i expect program print success after line of "ball". comparison not seem success.

i have tried comparison condition

if(!line.compare(test.c_str())){ 

still result same.

it seems picking line endings not appropriate platform. if don't control source of file trim() data read in using functions this:

https://stackoverflow.com/a/25385766/3807729

const char* ws = " \t\n\r\f\v";  // trim end (right) inline std::string& rtrim(std::string& s, const char* t = ws) {     s.erase(s.find_last_not_of(t) + 1);     return s; }  // trim beginning (left) inline std::string& ltrim(std::string& s, const char* t = ws) {     s.erase(0, s.find_first_not_of(t));     return s; }  // trim both ends (left & right) inline std::string& trim(std::string& s, const char* t = ws) {     return ltrim(rtrim(s, t), t); }  // ...  while(getline(myfile,line)) {     trim(line);     // ... } 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -