我在使用迭代器時遇到問題:
class Foo {
private:
std::istream_iterator<char> it_;
public:
Foo(std::string filepath) {
std::ifstream file(filepath);
it_ = std::istream_iterator<char>(file);
}
char Next() {
char c = *it_;
it_ ;
return c;
}
bool HasNext() { return it_ != std::istream_iterator<char>(); }
};
int main() {
Foo foo("../input.txt");
while (foo.HasNext()) {
std::cout << foo.Next();
}
std::cout << std::endl;
return EXIT_SUCCESS;
}
該檔案input.txt只是Hello, world!.
但是當我運行它時,它只列印H. 似乎與將迭代器存盤為成員變數有關?
uj5u.com熱心網友回復:
這里:
Foo(std::string filepath) {
std::ifstream file(filepath);
it_ = std::istream_iterator<char>(file);
}
您將迭代器存盤到file. 一旦這個建構式回傳files 解構式被呼叫并且所有的迭代器都ifstream變得無效。它類似于使用指向不再存在的物件的指標。您需要ifstream從中讀取,迭代器僅參考可以從檔案中提取的內容,但是如果檔案消失了,則無法從中提取。也存盤ifstream為成員。
您可以讀取第一個字符,因為已經std::istream_iterator從檔案中提取了第一個字符的構造。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/464680.html
