我想要在我的项目中使用 41 个输出文件来在其上写入文本。首先创建一个字符串数组list
为了命名这些输出文件,然后我尝试定义一个 ofstream 对象数组并使用list
命名它们,但我收到此错误'outfile' cannot be used as a function
。下面是我的代码:
#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 开始!)
- Call
.open(...)
on a 默认构造的 ofstream
打开一个文件
- Recommendations:
- 我建议反对
using namespace std;
(以下未更改)
- 我建议重复使用
stringstream
。这是很好的做法
- 更喜欢使用 C++ 风格的循环索引变量 (
for (int i = ....
)。这可以防止出现意外i
具有超额范围。
- 事实上,与时俱进并使用范围广泛
#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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)