我正在尝试创建 ifstream
对象数组,代码编译后我能够创建大小为 sizeargs-1 的
然而,一旦我尝试在其中一个 ifstream
对象数组ifstream
对象中打开一个文件,程序就会崩溃,这非常令人沮丧。
我尝试这样做的原因是我必须根据内存中 .ppm
文件的数量动态创建 ifstream
对象,这似乎是完美的解决方案,只需能够 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]);
}
最佳答案
int sizeargs = (sizeof(args)/sizeof(*args)); //counts number of .ppm files in array
不,它没有。计算结果为 sizeof(char**)/sizeof(char*)
,它始终为 1。sizeargs-1
因此为 0
,您您的数组中没有项目。您无法通过指向数组的指针找到数组的大小。需要使用argc
,即args
中的元素个数。
根据评论,您还应该避免使用可变长度数组,因为它们仅适用于编译器扩展,并且不是 C++ 标准的一部分。我建议改用 vector :
std::vector<std::ifstream> inputfiles(sizeargs-1);
关于c++ - C++ 中的 ifstream 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23134365/