如何从文件中读取,然后继续从cin读取?
How to read from a file, and then continue reading from cin?
在我的程序中,有一个游戏循环,它从文件中读取行,然后从标准输入中读取行。存档此内容的最佳方法是什么?
我试图通过以下方式将文件流缓冲区放入 cin 缓冲区 cin.rdbuf(filestream.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
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);
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 循环后如何继续阅读
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 失败后可以继续从流读取吗?
- 如何从文件中读取,然后继续从cin读取?
- 控制台将继续关闭,而不是读取 if 语句中的字符串
- 如何只要用户愿意就继续读取输入
- 如何使用 ifstream 打开文件并继续读取直到最后
- C++流继续读取相同的前 5 行
- 如何从文件中读取,直到读取到一个字符,然后跳过一些字符,再次继续读取
- C++在eof()之后继续读取文件
- 分部分读取文件,在最后读取的部分之后继续
- 结束函数,同时从该点继续读取文件
- 程序不会在输入文件中继续读取它
- 从 arduino 读取到 c++ 程序时继续接收 NULL