【问题标题】:Copying an ifstream to istream C++14 [duplicate]将 ifstream 复制到 istream C++14 [重复]
【发布时间】:2016-11-19 18:27:53
【问题描述】:

我想做这样的事情,但一直遇到错误,因为 istream 的复制赋值运算符受到保护。我想有一种方法可以在程序中的某个未知点将输入从 cin 切换到来自文件的输入。

#include <iostream>
#include <fstream>
using namespace std;

int main() {
   istream &in = cin;
   ifstream f{"file.txt"};
   in = f;
   // Then I want to read input from the file.
   string s;
   while(in >> s) {
     cout << s << endl;
   }
}

【问题讨论】:

  • 流不可分配/可复制。你到底想用in=f; 完成什么?这是没有意义的。只需直接在f 上使用operator&gt;&gt;

标签: c++ io c++14


【解决方案1】:

您不能“复制流”。流不是容器;这是一个数据流。

你似乎真的试图做的是重新绑定一个引用。好吧,您也不能这样做(实际上没有语法,因此您的编译器认为您正在尝试复制分配流本身),因此请改用指针:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
   istream* in = &cin;
   ifstream f{"file.txt"};
   in = &f;
   // Now you can read input from the file.
   string s;
   while(*in >> s) {
     cout << s << endl;
   }
}

确保只要in 指向它,f 就一直存在。

【讨论】:

    【解决方案2】:

    您可以通过使用rdbuf 重新分配流缓冲区来实现您想要的:

    in.rdbuf(f.rdbuf());
    

    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 2014-10-14
      • 2015-10-27
      • 1970-01-01
      • 2012-11-13
      相关资源
      最近更新 更多