2016-11-19 51 views
0

我想做类似这样的事情,但仍然遇到错误,关于istream的复制赋值运算符受保护。我想有一种方法可以将输入从cin切换到我的程序中某个未知点的文件输入。将ifstream复制到istream C++ 14

#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; 
    } 
} 
+0

流不分配/可复制。你究竟用'in = f;'来完成什么?这没有意义。只需在'f'上直接使用'operator >>'。 –

回答

3

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

你看上去真的试图做的是重新绑定一个引用。好了,你不能做,要么(有没有字面语法它,因此你的编译器认为你要复制的分配流本身),因此改为使用指针:

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

确保f只要in指向它就能存活下来。

1

你可以达到你想要的重新分配流缓冲带rdbuf

in.rdbuf(f.rdbuf()); 

demo