C++ while 循环和 ifstream 中的奇怪行为

Strange behavior in C++ while loop and ifstream

本文关键字:while 循环 ifstream C++      更新时间:2023-10-16

所以我有一个问题,当我从循环中的文件中读取输入时,我的函数将无法正常工作,例如:

ifstream in(inputFileName.c_str());  //input file is a string
    string word;
    while (in >> word){
        cout << word << endl;  //this behaves as it should n prints all words in file
        test.insert(word, 0);       //this function won't insert the words !
    }

但是如果我这样做

in >> word;
test.insert(word, 0);
in >> word;
test.insert(word, 0);
in >> word;
test.insert(word, 0);

....一切都很好!这对我来说真的很奇怪,任何想法会导致这种情况吗?

在我看来

,问题可能出在您的哈希表类中,test就是其中的一个实例。

如果没有一个很好的理由来做其他事情,我至少会考虑使用std::unordered_set

std::ifstream in(inputFilename); // `.c_str()` no longer required in C++11
// read the words into the set
std::unordered_set test {std::istream_iterator<std::string>(in),
                         std::istream_iterator<std::string>()};
// display the unique words:
std::cout << "Unique words:n";
std::copy(test.begin(), test.end(), 
          std::ostream_iterator<std::string>(std::cout, "n"));