2016-08-04 59 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

这不回答有关迭代器的问题。 –