使用ifstream读取浮点 [英] Using ifstream to read floats

查看:232
本文介绍了使用ifstream读取浮点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ifstream从.out文件读取一系列浮点数,但如果我以后输出,它们是不正确的。

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.

我输入的代码:

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();

我的输入文件:

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

现在测试,我只是读第一行 x y z ,我的输出是

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?

推荐答案

#include <fstream>
#include <strtk.hpp>   // http://www.partow.net/programming/strtk

#ifdef HAVE_BOOST
#include <boost/string/algorithm.hpp>
#endif

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    = " \t\r\n\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 ) )
{
// if you have boost available, they have a nice
// function that is great an removing beginnning and ending
// whitespace.  which can prevent parsing problems
// from different line endings.
#if HAVE_BOOST
    boost::algorithm::tritm( line );
#endif

    // strtk::parse combines multiple delimeters 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.

这篇关于使用ifstream读取浮点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆