use*_*370 1 c++ arrays iostream ifstream ofstream
我正在尝试创建一个ifstream对象数组,代码编译,我能够创建ifstream大小的对象数组sizeargs-1但是一旦我尝试ifstream在程序崩溃的其中一个对象中打开一个文件,这是非常令人沮丧的.
我尝试它的原因是我必须ifstream根据.ppm内存中的文件数量动态创建对象,这似乎是完美的解决方案,ifstream_array[1].open(args[0]);因为我需要.ppm同时从多个文件中读取文本.
如果这样做是不可能的; 这样做有另一种方法吗?
int main(int argc, char ** args)
{
//counts number of .ppm files in array
int sizeargs = (sizeof(args)/sizeof(*args));
ifstream inputfiles[sizeargs-1];
int incounter = 0;
//this is where the program crashes
inputfiles[incounter].open(args[0]);
}
Run Code Online (Sandbox Code Playgroud)
int sizeargs = (sizeof(args)/sizeof(*args)); //counts number of .ppm files in array
Run Code Online (Sandbox Code Playgroud)
不,它没有.这个求值为sizeof(char**) / sizeof(char*),总是为1 sizeargs-1,因此0你的数组中没有项目.您无法通过指向它的指针找到数组的大小.你需要使用argc,这是元素的数量args.
根据注释,您还应该避免使用可变长度数组,因为它们仅可用于编译器扩展,并且不是C++标准的一部分.我建议使用矢量代替:
std::vector<std::ifstream> inputfiles(sizeargs-1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
892 次 |
| 最近记录: |