Dynamic Array Allocation

I have a problem where I need to read in a text file with one column of REAL (i.e. float) data. Attached is a program that accomplishes this, but it requires apriori knowledge of the length of the file, in order to assign an array size to the variable input. In fortran I can open the file and have a counter advance each time the program moves to a new line and this will continue until it gets to the end of the file, even though it is not reading in any data. Once this is done, the counter is storing the number of rows of data and I can assign that variable to the array size, in essence it is dynamically allocating the array and then I can read in the data points. Is there a method of doing something similar in C++? In other words is there some method to determine the number of data points in the text file and then dynamically allocate the array "input[]" and then read in the data points associated with the variable "input[]"?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "Read_Columnar_File.h"

void Read_Columnar_File::Open_File(const std::string& str)
{
    float input[6];

    int i;
    std::ifstream inp(str,std::ios::in | std::ios::binary);
    if(!inp) {
        std::cout << std::endl << "Cannot Open " << str << std::endl;
    }
    for(i=0;i<5;i++) {
        inp >> input[i-1];
    }
    inp.close();
    
}
You can do the same thing in C++.

Read the file to determine the number of values then dynamically allocate an array of floats (or doubles).

1
2
3
4
5
6
 
  int num_val = 0;
  float * values;
  // Read file and increment num_val for each value
  values = new float [num_val];
  // Reposition the file to the beginning and read the values 


Perhaps an easier way is to use a std::vector.
1
2
3
4
5
 
  vector<float>  values; 
  float value;
  // read each value
  values.push_back (value);


The vector will expand automatically as needed to accomodate additional values.
Thank you, the use of vector worked well. However with respect to multiple columns of data it only produced more questions, which strangely is great to get these questions better here. I just posted a more detailed explanation of my most recent question titled "reading in multiple columns of data with std::vector". If you have any thoughts on my most recent question I would appreciate your input. Thank you for your help.
Topic archived. No new replies allowed.