gpt4 book ai didi

c++ - 如何从 ASCII 文件中读取数字 (C++)

转载 作者:IT老高 更新时间:2023-10-28 22:01:21 25 4
gpt4 key购买 nike

我需要读取如下所示的数据文件:

* 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

将这个文件读入 float 组的最优雅的方法是什么?

我知道如何将每一行读入一个字符串,并且我知道如何使用 atof() 将字符串转换为 float 。但是我该怎么做最简单的呢?

我听说过字符串缓冲区,这对我有帮助吗?

最佳答案

String Toolkit Library (Strtk)对您的问题有以下解决方案:

#include <iostream>
#include <string>
#include <deque>
#include <iterator>

#include "strtk.hpp"

int main()
{
std::deque<float> flist;
strtk::for_each_line("file.txt",
[&flist](const std::string& line)
{ strtk::parse(line," ",flist); }
);
std::copy(flist.begin(),flist.end(),
std::ostream_iterator<float>(std::cout,"\t"));
return 0;
}

更多示例可以在 C++ String Toolkit (StrTk) Tokenizer 中找到.

关于c++ - 如何从 ASCII 文件中读取数字 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1323824/

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