我需要读入如下所示的数据文件:
* SZA: 10.00
2.648 2.648 2.648 2.648 2.648 2.648 2.648 2.649 2.650 2.650
2.652 2.653 2.652 2.653 2.654 2.654 2.654 2.654 2.654 2.654
2.654 2.654 2.654 2.655 2.656 2.656 2.657 2.657 2.657 2.656
2.656 2.655 2.655 2.653 2.653 2.653 2.654 2.658 2.669 2.669
2.667 2.666 2.666 2.664 2.663 2.663 2.663 2.662 2.663 2.663
2.663 2.663 2.663 2.663 2.662 2.660 2.656 2.657 2.657 2.657
2.654 2.653 2.652 2.651 2.648 2.647 2.646 2.642 2.641 2.637
2.636 2.636 2.634 2.635 2.635 2.635 2.635 2.634 2.633 2.633
2.633 2.634 2.634 2.635 2.637 2.638 2.637 2.639 2.640 2.640
2.639 2.640 2.640 2.639 2.639 2.638 2.640 2.640 2.638 2.639
2.638 2.638 2.638 2.638 2.637 2.637 2.637 2.634 2.635 2.636
2.637 2.639 2.641 2.641 2.643 2.643 2.643 2.642 2.643 2.642
2.641 2.642 2.642 2.643 2.645 2.645 2.645 2.645
将这个文件读入一个浮点数组最优雅的方式是什么?
我知道如何将每一行读取为字符串,还知道如何使用atof()
将字符串转换为浮点型。但是我怎么才能做到剩下的最简单呢?
我听说过字符串缓冲区,这对我有帮助吗?
发布于 2009-08-24 22:40:39
使用STL算法的简单解决方案:
#include <vector>
#include <iostream>
#include <string>
#include <iterator>
struct data
{
float first; // in case it is required, and assuming it is
// different from the rest
std::vector<float> values;
};
data read_file( std::istream& in )
{
std::string tmp;
data d;
in >> tmp >> tmp >> d.first;
if ( !in ) throw std::runtime_error( "Failed to parse line" );
std::copy( std::istream_iterator<float>( in ), std::istream_iterator<float>(),
std::back_inserter<float>(d.values) );
return data;
}
如果确实需要使用数组,则必须首先分配该数组(如果知道数组大小,则可以动态分配或静态分配),然后可以使用相同的复制算法
// parsing the first line would be equivalent
float data[128]; // assuming 128 elements known at compile time
std::copy( std::istream_iterator<float>(is), std::istream_iterator<float>(),
data );
但我建议使用std::vector,即使在这种情况下,如果您需要将数据传递到一个接受数组的函数中,您可以始终将其作为指向第一个元素的指针进行传递:
void f( float* data, int size );
int main()
{
std::vector<float> v; // and populate
f( &v[0], v.size() ); // memory is guaranteed to be contiguous
}
https://stackoverflow.com/questions/1323824
复制相似问题