How to read float with scientific notation from file C++?

一世执手 提交于 2019-12-05 20:50:10
Björn Pollex

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.

Johnsyweb

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"));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!