kong kong - 1 month ago 10
C++ Question

reusing a stringstream to parse values from multiple strings in succession

I am trying to read in data from a text file but am not getting the right values. Only the values of width0 and height0 and width1 height 1 are right. All the values after the 2nd line are wrong. Can anyone tell me why ?

string line, thrash;
std::istringstream in;
ifstream myfile("camera_parameters.txt");

float width0, height0, width1, height1; // Initial and Final image sizes
float fx1, fy1, cx1, cy1; // L camera matrix
float fx2, fy2, cx2, cy2; // R camera matrix
float a1, b1, c1, d1, e1; // L camera distortion matrix
float a2, b2, c2, d2, e2; // R camera distortion matrix
float tx, ty, tz; // Trans from L to R camera
float r00, r01, r02, // Rotat from L to R camera
r10, r11, r12,
r20, r21, r22;

std::getline(myfile, line); in.str(line);
in >> thrash;
in >> width0 >> height0;
in.str(""); in.clear();

std::getline(myfile, line); in.str(line);
in >> thrash;
in >> width1 >> height1;
in.str(""); in.clear();

std::getline(myfile, line); in.str(line);
in >> thrash;
in >> tx >> ty >> tz;
in.str(""); in.clear();
cout << tx << " " << ty << endl;

std::getline(myfile, line); in.str(line);
in >> thrash;
in >> r00 >> r01 >> r02 >> r10 >> r11 >> r12 >> r20 >> r21 >> r22;
in.clear(); in.str(std::string());

std::getline(myfile, line); in.str(line);
in >> thrash;
in >> fx1 >> thrash >> cx1 >> thrash >> fy1 >> cy1;
in.clear(); in.str(std::string());

std::getline(myfile, line); in.str(line);
in >> thrash;
in >> a1 >> b1 >> c1 >> d1 >> e1;
in.clear(); in.str(std::string());

std::getline(myfile, line); in.str(line);
in >> thrash;
in >> fx2 >> thrash >> cx2 >> thrash >> fy2 >> cy2;
in.clear(); in.str(std::string());

std::getline(myfile, line); in.str(line);
in >> thrash;
in >> a2 >> b2 >> c2 >> d2 >> e2;
in.clear(); in.str(std::string());


Below are my data in a text file

S_00: 1.392000e+03 5.120000e+02
S_rect_00: 1.242000e+03 3.750000e+02
T_01: -5.370000e-01 4.822061e-03 -1.252488e-02
R_01: 9.993513e-01 1.860866e-02 -3.083487e-02 -1.887662e-02 9.997863e-01 -8.421873e-03 3.067156e-02 8.998467e-03 9.994890e-01
K_00: 9.842439e+02 0.000000e+00 6.900000e+02 0.000000e+00 9.808141e+02 2.331966e+02 0.000000e+00 0.000000e+00 1.000000e+00
D_00: -3.728755e-01 2.037299e-01 2.219027e-03 1.383707e-03 -7.233722e-02
K_01: 9.895267e+02 0.000000e+00 7.020000e+02 0.000000e+00 9.878386e+02 2.455590e+02 0.000000e+00 0.000000e+00 1.000000e+00
D_01: -3.644661e-01 1.790019e-01 1.148107e-03 -6.298563e-04 -5.314062e-02

Answer

After in >> width0 >> height0;, the EOF flag is set on in, which will prevent any further usage.

Associating the stream with new data via in.str(line) doesn't reset the flags, you will have to do that yourself via in.clear().

Comments