繁体   English   中英

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

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

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

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

您可以使一个函数接受对通用类型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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM