问题
I have a file with this format:
-0.0064785667 0.73900002 0.028505694 4.7858757e-39 315 218
-0.0051828534 0.73900002 0.028505694 4.6936954e-39 316 218
-0.0038818798 0.73799998 0.028467119 5.1546736e-39 317 218
-0.0025879198 0.73799998 0.028467119 5.6160217e-39 318 218
-0.0012939599 0.73799998 0.028467119 6.4461411e-39 319 218
I read it with this code:
using namespace std;
ifstream inputFile;
//Opens data file for reading.
inputFile.open(filePath.c_str());
//Creates vector, initially with 0 points.
vector<Point> data(0);
float temp_x,temp_y,temp_z,rgb=0,discard_1=0,discard_2=0;
//Read contents of file till EOF.
while (inputFile.good()){
inputFile >> temp_x >> temp_y >> temp_z >> rgb >> discard_1 >> discard_2;
data.push_back(Point(temp_x,temp_y,temp_z,rgb));
}
if (!inputFile.eof())
if (inputFile.fail()) cout << "Type mismatch during parsing." << endl;
else cout << "Unknow problem during parsing." << endl;
//Close data file.
inputFile.close();
Reading the scientific notation float results in a type mismatch.
How can I read all the numbers including the scientific notation float?
回答1:
The problem is probably your while-loop. Never use while(inputFile.good())
. Use this:
while (inputFile >> temp_x >> temp_y >> temp_z
>> rgb >> discard_1 >> discard_2) {}
This answer to a different question explains why. You might also be interested in this answer, which suggests a more elegant solution.
回答2:
Expanding upon Björn Pollex's answer with an example without any error-handling:
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
struct point
{
double x, y, z, rgb;
};
struct point_line: public point
{
int discard[2];
};
std::istream& operator >>(std::istream& is, point_line& in)
{
is >> in.x >> in.y >> in.z >> in.rgb >> in.discard[0] >> in.discard[1];
// TODO: Add your error-handlin
return is;
}
std::ostream& operator <<(std::ostream& os, const point& out)
{
os << " X: " << out.x
<< " Y: " << out.y
<< " Z: " << out.z
<< " RGB: " << out.rgb
;
return os;
}
int main()
{
std::ifstream points_file("points.txt");
std::vector<point> points;
std::copy(std::istream_iterator<point_line>(points_file),
std::istream_iterator<point_line>(),
std::back_inserter(points));
std::copy(points.begin(),
points.end(),
std::ostream_iterator<point>(std::cout, "\n"));
}
来源:https://stackoverflow.com/questions/8986488/how-to-read-float-with-scientific-notation-from-file-c