I'm working on an experiment that requires me to switch over to C++, which I'm still learning. I need to read data from a file into a 2D array, where the data in the file is composed of floating point numbers, laid out in a matrix format. However, each row of the matrix in the data file has a different number of columns, for example:
1.24 3.55 6.00 123.5
65.8 45.2 1.0
1.1 389.66 101.2 34.5 899.12 23.7 12.1
The good news is that I know the maximum number of possible rows/columns the file might have, and at least right now, I'm not particularly worried about optimization for memory. What I would like is to have a 2D array where the corresponding rows/columns match those of the file, and all the other elements are some known "dummy" value.
The idea I had was to loop through each element of the file (row by row), recognize the end of a line, and then begin reading the next line. Unfortunately I'm having trouble executing this. For example:
#include <iostream>
#include <fstream>
int main() {
const int max_rows = 100;
const int max_cols = 12;
//initialize the 2D array with a known dummy
float data[max_rows][max_cols] = {{-361}};
//prepare the file for reading
ifstream my_input_file;
my_input_file.open("file_name.dat");
int k1 = 0, k2 = 0; //the counters
while (!in.eof()) { //keep looping through until we reach the end of the file
float data_point = in.get(); //get the current element from the file
//somehow, recognize that we haven't reached the end of the line...?
data[k1][k2] = next;
//recognize that we have reached the end of the line
//in this case, reset the counters
k1 = 0;
k2=k2+1;
}
}
And so I haven't been able to figure out the indexing. Part of the problem is that although I'm aware that the character "\n" marks the end of a line, it is of a different type compared to the floating point numbers in the file, and so I'm at a loss. Am I thinking about this the wrong way?