I am currently trying to learn the basics of C++ by converting one of my older fortran programs into c++, but I have hit a wall when it comes to how to read in data to arrays. My aim is mainly to write scientific programs that I can use myself and large data files and their manipulation are at the core of those.
My data files comes in the form <float float float ...> one example is.
1.231451 343215.12 0.2
This format is repeated throughout all data files, there are no char or int values only float. The data needs to go into their separate arrays.
All data files have the same length, lets say 100 values. So far I figured out how to open the file and get the values printed to screen, but I am at a total loss about what commands and what format to write to get out data of the above type in c++. I have tried to search for a similar topic but it seems that people are only interested in copying in char values or entire lines into arrays and not formatted floating point data.
int index = 0; // keep track of current array element
while ( Inputfile.good() && index < 100 ) // checks also if input was bad, not only for end of file. index < 100 prevents errors with the array
{
Inputfile >> Pdata[index++]; // read from file into the array and increase index by one
}
I tried to use what you suggested, and while I did not expect it to work just like that it is something to work with which is better then constant compiler errors.
Also just to clarify the data is looking like this in the file and each column needs to go into a specific array.
1.0 4134.0 3213.1
2.0 324.00 8545.4
3.0 8572.1 3214.1
...
So first column go in an array called Dataarray1 etc. Hope that is more clear then what I wrote before.
I am sure this problem is awkwardly simple once I get it down.. it was when I learned to do it in python and fortran. Fortran was just using a built in command ios and then it worked. The loop to do it looks like this... painfully simple once understood what was going on.
1 2 3 4 5 6
n=0
do
read ("Filepointer" ,*,iostat=ios) Dataarray1(n+1), Dataarray2(n+1)
if (ios /= 0) exit
n = n + 1
enddo
That would take all numbers up to the first space in a line then put it into Dataarray1 then take the next number after a space and put it into Dataarray2, and one can just keep adding arrays if the file had more numbers on the same line. And when it ran out of lines it would stop the loop.
But your idea about using a multi dimensional array might be worth investigating once I get the basics down and need to tune performance later, so thanks a lot for that idea Bazzy