gpt4 book ai didi

c++ - 检查字符串是否相同C++

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:03:01 25 4
gpt4 key购买 nike

对于我的情况,我必须检查 2 个字符串是否相同。我得到的问题是,无论我输入什么,无论我输入什么,我都会得到一个真正的值(value)。

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

出于测试目的,我使用了这样的 do 循环来输入要测试的内容,与我加载的 dictionary.txt 文件进行比较。

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

最佳答案

那是因为当字符串相等时,compare 实际上返回 0。如果字符串不相等,它将返回一个更高或更低的值,并且 if 将评估为真,如您所见。

在像 Java 和 C# 这样的语言中,使用像 equals 这样的方法来比较非基元是很常见的,但在 C++ 中,最好只使用 ==

关于c++ - 检查字符串是否相同C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16696559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com