gpt4 book ai didi

c++ - 使用 ifstream 读取 float

转载 作者:可可西里 更新时间:2023-11-01 16:38:12 24 4
gpt4 key购买 nike

我正在尝试使用 ifstream 从 .out 文件中读取一系列 float ,但如果我之后输出它们,它们就不正确了。

这是我的输入代码:

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 yz,我的输出是

1 0 2

关于为什么我没有得到正确的输出有什么想法吗?

最佳答案

#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 = " \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 ) )
{
// 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
}
}

我就是这样解决的。您可以选择自己的方式来解析数据。

关于c++ - 使用 ifstream 读取 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22100662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com