在我的程序中有一个游戏循环,它从文件中读取行,然后从标准输入中读取行。什么是归档这个最好的方法?如何从文件中读取,然后继续从cin读取?
我试图通过 cin.rdbuf(filestream.rdbuf())将文件流缓冲区放入cin缓冲区中; 但它不起作用。读取结束在文件流的最后一行之后。
在我的程序中有一个游戏循环,它从文件中读取行,然后从标准输入中读取行。什么是归档这个最好的方法?如何从文件中读取,然后继续从cin读取?
我试图通过 cin.rdbuf(filestream.rdbuf())将文件流缓冲区放入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);
}
您可以接受的一般类型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
你的意思是说,你想要执行完全相同的操作,但有时与文件,有时与'std :: cin'? – Galik
好像你让这个过于复杂。从文件中读取,直到你不应该从cin读取。不要试图将它们组合成一个单一的流。 –