inourss
inourss

Reputation: 73

Array size defined by number of lines from input file

I'm reading a file and putting entries in an array but I want to define the size of the array from the number of lines contained in an input file.

Here's my code:

int main(int argc, char* argv[])
{
   ifstream infile;

   int num = 0;
   int id[9999];
   int size = sizeof id/ sizeof id[0];

   infile.open("test.dat");
   if(infile.fail())
   {
       cout << "error" << endl;
       return 1;
   }

   while(!infile.eof())
   {

    infile >> id[num];

    ++num;
   }

// Then I do whatever I want...
 for(int i=0;i<size;i++)
   {
     ...
   }

The problem is that I have to define manually the size of id[] depending on the number of lines contained in my test.dat file (here for example 9999).

Is there a way to automatically define the size of the id[] ?

Upvotes: 1

Views: 1021

Answers (1)

gsamaras
gsamaras

Reputation: 73366

Since this is C++, the best approach would be to use an std::vector.

When you perform a push_back() operation on a vector, then its size will automatically increase by one, and you won't have to worry about the size, since it will adjust to insertions/deletions you perform.

So your code would something like this now:

#include <vector>

int main(int argc, char* argv[])
{
   ifstream infile;

   int num = 0;
   std::vector<int> id;

   infile.open("test.dat");
   ...

   int value;
   while(!infile.eof())
   {
     infile >> value;
     id.push_back(value);
   }

   for(int i = 0; i < id.size(); i++)
   {
      std::cout << id[i] << "\n";
   }
   ...
}

Now if you want to actually stick to raw arrays (which you would do in C for example), then one possible approach (not suggested though) would be to read the whole file once and count how many IDs are there. Then, dynamically allocate memory for an array of that size. Afterwards, you would need to rewind the file pointer at the start of the file, and start parsing the file in order to fill your array. When you won't longer need that array, you must free the memory you allocated for it.

Notice that the array has to be dynamically allocated in this case, since variable-sized arrays are not Standard C++.

Upvotes: 3

Related Questions