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

时间:2017-07-15 02:59:08

标签: c++ c++14

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

我试图将文件流缓冲区放入cin缓冲区中     cin.rdbuf(filestream.rdbuf()); 但它不起作用。读取结束于文件流的最后一行之后。

2 个答案:

答案 0 :(得分:1)

您可以创建一个接受对常规类型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

答案 1 :(得分:0)

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);
}