Question

I need to have a series of files open at the same time. It'd be easier to handle the files with array of ifstream object. I got an error declaring

ifstream fin[file_count];

error: variable length array of non-POD element type 'ifstream'
      (aka 'basic_ifstream<char>')
  ifstream fin[fcount];

What is wrong? I see people do this at How do I create an array of ifstream objects and how can I populate that array with numbered text files?

Was it helpful?

Solution

You cannot create a static array of a non-fixed length (file_count gets its value in runtime if it is not a constant).

You can however use an array of pointers to a stream, which might ease your task. Consider it as an option:

ifstream* fin = new ifstream[file_count];
...
delete [] fin;

OTHER TIPS

The problem is that you are declaring a variable size array which is not allowed in C++.

When declaring an array in C++:

int i[size];

The variable size must either be a constant integral value

In order to create a C++ array with a variable size you need to use dynamically allocated memory:

int* i;
i = new int[size];

Now size can be a variable. The problem is of course that not only is i not a pointer and has to be used as such, it also has to be deallocated later or you will have memory leaks, i.e. memory space your program has technically reserved but isn't using for anything.

More on dynamic memory here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top