Using ifstream to read floats(使用 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
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.
这篇关于使用 ifstream 读取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 ifstream 读取浮点数
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01