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);
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 ==
.
There should be an operator==
for std::string
available for a more natural feeling comparison.
if(input == getWordFromDictionary(counter)) { ... }
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