Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c++ - Using ifstream to read floats

I'm trying to read a series of floats from a .out file using ifstream, but if I output them afterwards, they are not correct.

This is my input code:

float x, y, z;

ifstream table;
table.open("Resources/bones.out");
if (table.fail())
{
    cout << "Can't open table" << endl;
    return ;
}

table >> x;
table >> y;
table >> z;

cout << x << " " << y << " " << z << endl;

table.close();

My input file:

0.488454 0.510216 0.466979
0.487242 0.421347 0.472977
0.486773 0.371251 0.473103
...

Now for testing, i'm just reading the first line into x y and z and my output is

1 0 2

Any ideas as to why I'm not getting the right output?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
#include <fstream>
#include <strtk.hpp>   // http://www.partow.net/programming/strtk

std::string filename("Resources/bones.out");

// assuming the file is text
std::fstream fs;
fs.open(filename.c_str(), std::ios::in);

if(fs.fail())  return false;   

const char *whitespace    = " 
f";

std::string line;
std::vector<float> floats;
std::vector<std::string> strings;
float x = 0.0, y = 0.0, z = 0.0;
std::string xs, ys, zs;

// process each line in turn
while( std::getline(fs, line ) )
{
    // Removing beginning and ending whitespace
    // can prevent parsing problems from different line endings.
    // formerly accomplished with boost::algorithm::trim(line)

    strtk::remove_leading_trailing(whitespace, line);


    // strtk::parse combines multiple delimiters in these cases

    if( strtk::parse(line, whitespace, floats ) ) 
    {
         std::cout << "succeed" << std::endl;
         // floats contains all the values on the in as floats
    }

    if( strtk::parse(line, whitespace, strings) ) 
    {
         std::cout << "succeed" << std::endl;
         // strings contains all the values on the in line as strings
    }

    if( strtk::parse(line, whitespace, x, y, z) ) 
    {
         std::cout << "succeed" << std::endl;
         // x,y,z contain the float values.  parse fails if more than 3 floats are on the line
    }

    if( strtk::parse(line, whitespace, xs, ys, zs) ) 
    {
         std::cout << "succeed" << std::endl;
         // xs,ys,zs contain the strings.  parse fails if more than 3 strings are on the line
    }
}

This is how I would solve it. You can pick your way to parse the data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...