C++中的流数组
Array of fstream in C++
我正在使用NTL库编写算法(这是一个C++库(。现在我有 N 个文件要编辑,我必须同时创建/打开它们。我尝试为 N 文件指针动态分配空间,但代码有问题。代码片段如下所示:
P1 = (char **)calloc(n+1, sizeof(char *));//P1 is used to save file names
for(i=1; i<=n; i++)
{
P1[i]=(char *)calloc(20, sizeof(char ));
sprintf(P1[i],"P1_%d.txt",i);
}
ifstream *fin = (ifstream *)calloc(n+1, sizeof(ifstream));
for(i=1; i<=n; i++)
{
fin[i].open(P[i]);
}
当程序在 Linux 中运行时,它告诉我存在分段错误。
由于 N 不大于 200,当我尝试使用
ifstream fin[200]
而不是
ifstream *fin = (ifstream *)calloc(n+1, sizeof(ifstream));
程序运行。
我刚刚学了C,但没有学C++,我真的不知道fstream
课是如何工作的。你能告诉我是否有一些更好的方法可以同时打开N个文件吗?
calloc
只会分配内存,但ifstream
是复杂类型。它有构造函数,应该在对象创建时调用。我认为你应该阅读一些关于C++的文档/书籍。您应该使用新表达式在C++中分配内存。顺便说一句,如果您使用现代C++编译器,最好使用智能指针(例如unique_ptr(。此外,当您想要在编译时存储未知的对象计数时,最好使用 vector。在这种情况下,仅使用 vector<ifstream>
会更简单
// includes for vector and unique_ptr.
#include <vector>
#include <memory>
vector<ifstream> streams;
for (int i = 0; i < n; ++i)
{
streams.push_back(ifstream(P[i]));
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '