2016-08-04 99 views
2

我有一個文件需要在運行時多次打開。每次將一些文本添加到文件中。下面是代碼:重複使用流迭代器

ofstream fs; 
    fs.open(debugfile, fstream::app); 
    ostream_iterator<double> output(fs, " "); 
    copy(starting_point.begin(), starting_point.end(), output); 
    ... 
    fs.open(debugfile, fstream::app); 
    ostream_iterator<double> output1(fs, " "); 
    copy(starting_point.begin(), starting_point.end(), output1); 

我的問題是,我可以用一個流迭代器「輸出」每次我打開該文件時,如一些方法來清理它?

感謝

+7

爲什麼不把可重用代碼的函數和調用該函數多次? – NathanOliver

+0

那是對的。我可以這樣做。 – colddie

回答

1

您可以使用下面的代碼:

ofstream fs; 
fs.open(debugfile, fstream::app); 
ostream_iterator<double> output(fs, " "); 
copy(starting_point.begin(), starting_point.end(), output); 
... 
fs.open(debugfile, fstream::app); 
output = ostream_iterator<double>(fs, " "); 
copy(starting_point.begin(), starting_point.end(), output1); 

這裏相同的變量output用於存儲迭代器,但迭代器本身是從頭開始創建並分配給使用operator =這個變量。

0

對於我來說,沒有任何事情可以解決(appart重新分配值)。

只是不要忘記前重新打開關閉並清除流:

std::ofstream file("1"); 
// ... 
file.close(); 
file.clear(); // clear flags 
file.open("2"); 

來自:C++ can I reuse fstream to open and write multiple files?

+1

這不回答有關迭代器的問題。 –