C ++中的Ofstream数组 [英] Array of Ofstream in c++
本文介绍了C ++中的Ofstream数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在我的项目中使用41个输出文件来在它们上写文本.首先创建一个字符串数组list
来命名这些输出文件,然后我尝试定义ofstream对象的数组并使用list
来命名它们,但是出现此错误'outfile' cannot be used as a function
.下面是我的代码:
I want 41 output files to use in my project to write text on them. first create a string array list
to name those output files then I tried to define an array of ofstream objects and use list
to name them, but I get this error that 'outfile' cannot be used as a function
. Below is my code:
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std ;
int main ()
{
string list [41];
int i=1;
ofstream *outFile = new ofstream [41];
for (i=1;i<=41 ;i++)
{
stringstream sstm;
sstm << "subnode" << i;
list[i] = sstm.str();
}
for (i=0;i<=41;i++)
outFile[i] (list[i].c_str());
i=1;
for (i=1;i<=41;i++)
cout << list[i] << endl;
return 0;
}
推荐答案
请参见以下修补程序:
- 请勿使用
new
,除非您必须这样做(泄漏所有文件并且未正确销毁它们会导致数据丢失;如果未正确关闭它们,则未刷新ofstreams,以及未决的输出缓冲区将会丢失) - 使用正确的数组索引(从0开始!)
- 在默认构造的
ofstream
上调用.open(...)
打开文件 - 建议:
- 我建议不要使用
using namespace std;
(以下未更改) - 我建议重用
stringstream
.这是一个好习惯 - 首选使用C ++样式的循环索引变量(
for (int i = ....
).这样可以防止i
范围过大带来的意外. - 实际上,与时俱进,并在一定范围内使用
- 我建议不要使用
- don't use
new
unless you have to (you were leaking all files and not properly destructing them will lead to lost data; ofstreams might not be flushed if you don't close them properly, and the pending output buffer will be lost) - Use proper array indexing (starting from 0!)
- Call
.open(...)
on a default-constructedofstream
to open a file - Recommendations:
- I'd recommend against
using namespace std;
(not changed below) - I recommend reusing the
stringstream
. This is is good practice - Prefer to use C++-style loop index variables (
for (int i = ....
). This prevents surprises fromi
having excess scope. - In fact, get with the times and use ranged for
- I'd recommend against
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream outFile[41];
stringstream sstm;
for (int i=0;i<41 ;i++)
{
sstm.str("");
sstm << "subnode" << i;
outFile[i].open(sstm.str());
}
for (auto& o:outFile)
cout << std::boolalpha << o.good() << endl;
}
这篇关于C ++中的Ofstream数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文