C++提取文本文件不重复单词失败:if语句始终返回0求排查建议
排查C++提取不重复单词时重复内容无法过滤的问题
嘿,我一眼就瞅出你代码里的核心问题了——你的checkifexist函数永远返回0,是因为它根本没在你存单词的那个vector里检查!
问题根源
你在checkifexist函数里新建了一个reading类的对象readingobject,这是个局部变量,和主函数里那个存了单词的readingobject完全是两个独立的实例!这个局部对象的words容器是空的,所以遍历的时候永远找不到匹配的单词,自然返回0,导致所有单词都会被无脑添加到主函数的words里,重复内容就这么来了。
修正方案
给你两种靠谱的解决办法,按需选:
方案1:让检查函数接收主函数的vector作为参数
把checkifexist改成直接接收要检查的单词和目标vector,这样就能访问到真正存了单词的容器了:
// 改成bool返回更符合语义,也可以保留int,看你习惯 bool checkifexist(const string& word, const vector<string>& words) { for (const string& w : words) { if (word == w) { return true; } } return false; }
然后在主函数里调用的时候,把主对象的words传进去:
while (inFile >> readingobject.word) { // 这里顺便改了循环条件,避免多读一次最后一个单词 if (checkifexist(readingobject.word, readingobject.words)) continue; cout << readingobject.word << endl; readingobject.words.push_back(readingobject.word); }
方案2:把检查函数改成类的成员函数
既然checkifexist是用来检查reading类里的words,不如直接把它变成类的成员函数,这样它就能直接访问当前对象的words了:
class reading { public: string word; vector<string> words; // 成员函数,直接访问本对象的words bool checkifexist(const string& word) { for (const string& w : words) { if (word == w) { return true; } } return false; } };
主函数里调用的时候就简单多了:
while (inFile >> readingobject.word) { if (readingobject.checkifexist(readingobject.word)) continue; cout << readingobject.word << endl; readingobject.words.push_back(readingobject.word); }
额外优化建议
- 别用
while (!inFile.eof())这种循环方式!它会导致最后一个单词被读取两次,因为文件结束的eof标志要在尝试读取失败后才会被设置,正确的写法是while (inFile >> readingobject.word),读取失败时自动退出循环。 - 如果追求效率和简洁,可以用
std::unordered_set来存储单词,它会自动帮你去重,不需要自己写检查函数:
#include <iostream> #include <fstream> #include <unordered_set> using namespace std; int main() { unordered_set<string> uniqueWords; ifstream inFile("Book.txt"); if (!inFile) { cout << "file didn't open" << endl; exit(1); } string word; while (inFile >> word) { uniqueWords.insert(word); // 插入时自动去重 } // 输出所有不重复的单词 for (const string& w : uniqueWords) { cout << w << endl; } return 0; }
内容的提问来源于stack exchange,提问作者Mohammad
相关产品推荐
相关产品推荐

