如何从文件中读取,然后继续从cin读取?

How to read from a file, and then continue reading from cin?

本文关键字:读取 继续 cin 然后 文件      更新时间:2023-10-16

在我的程序中,有一个游戏循环,它从文件中读取行,然后从标准输入中读取行。存档此内容的最佳方法是什么?

我试图通过以下方式将文件流缓冲区放入 cin 缓冲区 cin.rdbuf(filestream.rdbuf(((; 但它不起作用。读取在文件流的最后一行之后立即结束。

您可以创建一个接受对常规类型引用的函数std::istream因为文件输入和标准输入都继承自std::istream,因此它们都可以通过引用此类函数来传递:

void do_regular_stuff(std::istream& is)
{
std::string line;
std::getline(is, line);
// yada yada
// use the stream is here ...
}
// ... in the game loop ...
std::ifstream ifs(input_file);
do_some_regular_stuff(ifs); // do it with a file
// ...
do_some_regular_stuff(std::cin); // now do it with std::cin

iostream 类被设计为多态使用。因此,只需使用指向文件流的指针,当它耗尽时,将其设置为指向 cin。喜欢这个:

std::ifstream fin("filename");
std::istream* stream_ptr = &fin;
std::string line;
while (something) {
if (!std::getline(*stream_ptr, line)) {
if (stream_ptr == &std::cin) {
// both the file and standard input are exhausted
break;
}
fin.close();
stream_ptr = &std::cin;
continue; // need to read line again before using it
}
something = process(line);
}