2016-11-19 52 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