在我的程序中有一个游戏循环,它从文件中读取行,然后从标准输入中读取行。存档的最佳方式是什么?
我试图通过以下方式将文件流缓冲区放入 cin 缓冲区 cin.rdbuf(文件流.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
关于c++ - 如何从一个文件中读取,然后继续从cin中读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45114035/