Fill a vector by reading a file

Hey guys,

I try to write a class matrix and I want to fill the matrix by reading a txt file.

How to read and save a string I know, but how does it works with double values ?

My code looks like that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include<ostream>
#include<string>
#include<fstream>

using namespace std;

int main ()
{
double a[9]; // Space for a 3x3 Matrix, saved as a vector

string line;
ifstream myfile ("matrixelements.txt");
if(myfile.is_open())
{
   while (getline (myfile.line))
   {
     cout<<line<<endl;
   }
   myfile.close();
}
else cerr<<"Unable to open file"<<endl;
}


The values are saved in the file matrixelements.txt like this:
 
1 2 0 4 6 9 3 1 5


Thanks a lot for help
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
#include<ostream>
#include<string>
#include<fstream>

using namespace std;

int main ()
{
double a[9]; // Space for a 3x3 Matrix, saved as a vector (technically it is an array)

string line;
ifstream myfile ("matrixelements.txt");
if(myfile.is_open())
{
   int i = 0;
   while ( i < 9 && myfile >> a[i] )
   {
     cout << a[i] << " ";
     i++;
   }
   myfile.close();
}
else cerr<<"Unable to open file"<<endl;
}

Thanks a lot for your help :-)
It works like I want.
Topic archived. No new replies allowed.