Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if strings are the same c++

For my case, I have to check if 2 strings are the same. The probelm I'm getting, is that No matter what I input, I'm getting a true value regardless of what I put in.

bool Dictionary::checkIfWordExists(string input){
for(int counter=0;counter<234;counter++){
    if(input.compare(getWordFromDictionary(counter))){
        return true;
    }
}
return false;}

For testing purposes I used a do loop like this to type in stuff to test in comparison to the dictionary.txt file that I loaded.

do{
    cout<<"enter something you sexy beast"<<endl;
    string test;
    cin>>test;
    if(loadedDictionary.checkIfWordExists(test)){
        cout<<"yes"<<endl;
    }else{
        cout<<"no"<<endl;
    }
}while(true);
like image 534
Michael Kimin Choo Avatar asked May 22 '13 16:05

Michael Kimin Choo


2 Answers

That's because compare actually returns 0 when the strings are equal. If the strings are not equal, it will return a value higher or lower and the if will evaluate to true, as you are seeing.

It is common in languages like Java and C# to use methods like equals to compare non-primitives, but in C++ it is preferably to just use ==.

like image 68
Overv Avatar answered Oct 16 '22 06:10

Overv


There should be an operator== for std::string available for a more natural feeling comparison.

if(input == getWordFromDictionary(counter)) { ... }
like image 30
andre Avatar answered Oct 16 '22 07:10

andre