This should fix your problem. It will parse all rows and place each line in a string stream. It then parses the string stream and streams the elements into doubles. It should work for any combination of rows and column elements.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main(){
// Open file
ifstream fileStream;
fileStream.open("myIniFile.txt");
// Initialize variables
string lineString;
int counter=0;
vector<vector<double> > myData; // Matrix which holds all data
vector<double> myLine; // Temporary vector to hold each row
double currentNumber;
// Read file
while(!fileStream.eof()){
++counter;
getline(fileStream,lineString); // Stream this line in a string
if (lineString!=""){ // If empty, exit
cout<<"Line #"<<counter<<" : "; // Print
cout<<lineString<<endl; // output
stringstream myS_stream(lineString);
while(myS_stream>>currentNumber){ // Important as a simple break condition will read the last element twice
cout<<"\tFound double number in string stream : "<< currentNumber<<endl;
myLine.push_back(currentNumber);
}
myData.push_back(myLine);
myLine.clear();
}
}
fileStream.close(); // Close file
// Print your data
cout<<"\nMy data is : "<<endl;
for (auto row : myData){
cout<<"\t";
for (auto element : row){
cout<<" "<<element;
}
cout<<endl;
}
// Convert to the format you want, but I suggest using std::vector
// if you can help it
double *monthRain = &myData.at(0)[0];
return 0;
}
2
solved How do I read a line of 12 numbers from a file and store it into an array?