small problem with istringstream and 2d vector
Jan 17, 2010 at 4:25pm UTC
Hi everyone,
I have troubles with reading floats from a file and writing it into a 2d vector. Basically, I have 3 coordinates (x,y,z) of some points which I want to store in a 2d vector. This is what I have so far:
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
if (argc != 2){
cout << "need a file..." << endl;
return 1;
}
int i=1;
float x,y,z;
string line;
vector< vector<float > > basis;
vector<float > row;
ifstream fin(argv[1]);
istringstream inputString(line);
while (i<4 && getline(fin, line) ){
inputString >> x >> y >> z;
row.push_back(x);
row.push_back(y);
row.push_back(z);
basis.push_back(row);
row.clear();
i++;
}
for (int l=0; l<3; l++){
for (int m=0; m<3; m++){
cout << basis[l][m] << " " ;
}
cout << endl;
}
return 0;
}
The input file has the following format:
e.g.:
1.33939344 3.498494944 1.33891
8.8484844 12.39398 4.59582111
23.9333 7.7893933 5.2323323
etc.
And this is the result I get printed on the screen:
0 0 5.89483e-39
0 0 5.89483e-39
0 0 5.89483e-39
So, it doesn't work. I don't see the mistake. Can anyone help me?
Last edited on Jan 17, 2010 at 4:25pm UTC
Jan 17, 2010 at 5:03pm UTC
I solved it. I have to place the line
istringstream inputString(line);
into the while loop. Then everything works fine.
1 2 3 4 5 6 7 8 9 10
while (i<4 && getline(fin, line) ){
istringstream inputString(line);
inputString >> x >> y >> z;
row.push_back(x);
row.push_back(y);
row.push_back(z);
basis.push_back(row);
row.clear();
i++;
}
Topic archived. No new replies allowed.