c++ - 如何从一个文件中读取,然后继续从cin中读取?

标签 c++ c++14

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

我试图通过以下方式将文件流缓冲区放入 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/

相关文章:

c++ - 子进程中的间歇性文件访问错误

python - Ctypes:将指针传递给使用sprintf的dll函数时, “Debug assertion failed”(string!= NULL)

c++ - Qt C++ 连接QPushButton 点击

C++ - 用户空间代码中的二级保护代码

c++ - 如何返回带有捕获的 unique_ptr 的 lambda

c++ - 由于哪个版本的 GCC 支持 C++14?

c++ - MSVC12中不允许使用默认参数中的模板类实例化吗?

c++ - 使用 C++14 的具有多个返回类型的 decltype(auto)

C++11 : Recursion in a stacked variadic struct (I get an linker error)

c++ - 部分特化的模板子类化