[英]Strange behavior in C++ while loop and ifstream
所以我有一個問題,當我從循環內的文件中讀取輸入時,我的功能將無法正常工作:
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"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.