假定相同的字符串之间的比较失败' == '比较



我正在尝试在字典文件中读取单词对象的向量,然后我对其进行迭代并将对象的单词与用户输入的内容进行比较。

但是,当在 Dictionary::wordFind() 中使用应与单词对象的单词(如"aa")相同的单词进行比较时,它无法正确进行比较。

没有输出任何错误,wordFind() 中的 if 语句由于某种原因没有实现。

字典.txt

aa
acronym for Associate in Arts a college degree granted for successful completion of a two-year course of study in arts or general topics;  Alcoholics Anonymous.
n
aaas
the American Association for the Advancement of Science an organization with headquarters in Washington D.C..
n

字典.cpp

void Dictionary::loadDictionary() {
ifstream dicFile("dictionary.txt");
string word, def, type, whitespace;
if (dicFile.is_open())
{
while (!dicFile.eof())
{
getline(dicFile, word);
getline(dicFile, def);
getline(dicFile, type);
getline(dicFile, whitespace);
Word word1(word, def, type);
wordObjects.push_back(word1);
}
dicFile.close();
}
}
void Dictionary::wordFind(string wordToFind) {
for (Word test : wordObjects)
{
if (test.getWord() == wordToFind)
{
cout << "Word found!" << endl;
cout << "Word: " << test.getWord() << "nn" << "Definition: " << "n" << test.getDef();
}
}
cout << "Word not found" << endl;
}

字.cpp

Word::Word(string _word, string _def, string _type) {
word = _word;
def = _def;
type = _type;
}
string Word::getWord() {
return word;
}
string Word::getDef() {
return def;
}
string Word::getType() {
return type;
}

主.cpp

int main()
{
Dictionary dic;
dic.loadDictionary();
if (menuChoice == 1)
{
string wordSearch;
cout << "Please enter your word: " << endl;
cin >> wordSearch;
dic.wordFind(wordSearch);
}

我注意到使用cout << wordObjects[2].showWord();(它将输出单词"aaas",如上面的字典.txt所示),输出似乎在单词的字母之间有空格,如下面的链接所示。 (我试图只添加图像,但我没有足够的业力。相信我,这不会是一个令人讨厌的链接) https://i.ibb.co/t4053Tf/12221222222222121212.png

我不确定为什么会发生这种情况,我想知道是否有人知道为什么我的代码会产生这种行为。

任何建议将不胜感激!

编辑:感谢保罗桑德斯关于Unicode字符的评论,我重新创建了字典.txt但将其保存在ANSI中,它似乎已经解决了我的问题。谢谢!

由于您使用的是 getline,虽然这可能不是您的问题,但您的单词后面可能会有空格,这些空格也会成为字典的一部分。从文件读取时应使用空格分隔符。

我建议先在控制台中输出字典单词,以便您知道它已正确存储。

最新更新