简体   繁体   中英

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

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 == .

应该有一个operator== std::string可用于更自然的感觉比较。

if(input == getWordFromDictionary(counter)) { ... }

You need to explicitly compare the result of compare with 0 . Here is what the return values mean:

0 => The compared strings are equal

<0 => Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.

>0 => Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.

See here for the detailed explanation on std::string::compare .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM