我正在尝试创建一个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]);
}
最佳答案
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/