I am trying to read floating point numbers from a file into a dynamically allocated 2D array. I am using c++.
In my .txt file the elements of a row are separated by a tab space each and each row starts on a new line.
My question is –
Can I increase the size of my array based on the no. of elements (rows and columns) present in the file? If so, please suggest a way to do it.
I thought of writing the no. of rows and columns on the first line of the text file and reading them in the beginning to set the limits of the loop which will allocate the space for my array. Is there a better way to do it, perhaps based on the formatting of the text file? This way, I think it will be closer to a streaming data kind of a scenario.
Thanks in advance.
Akhil
Rather than using an array, consider using a
std::vector, which automatically resizes. In C++, this is strongly preferred to using a raw array, since it’s safer and hides the resource management.In fact, using a
std::vectorin conjunction with the stream libraries, it’s very easy to read a file of tab-separated floating-point values:Or, alternatively:
However, the above code will read a 1D array of floats, rather than the 2D array you wanted. To read a 2D array, one option is to read one line of the file at a time, then use a modification of the above code to break that line into individual floats. For example:
Hope this helps!