用c++解析TXT文件
parsing a txt file in c++
你好,我是从c#来的,最近一直在使用c++,我需要帮助。我有一个文本文件(500mb),我需要加载到一个数组(矩阵)。文本文件的格式为
specimen date result
E1 111111 0.5
我怎么能把这个结果提取出来,只把它放入矩阵中,每一列代表一个不同的样本?我知道在c#中我可以很容易地解析这个,但我不知道如何在c++中做到这一点谢谢你的帮助,我只是想知道我需要知道的命令或功能
E1 ............En
result@ time 1 .................
. .
. . . . . . . ..
result@time n .................
有7000个标本,3年的数据,结果从0.1到20000
您可以使用标准库中的文件流,以及格式化的输入:
std::vector< double > results;
std::ifstream input( "yourfile.txt" );
std::string specimen;
int date;
double result;
while( ( input >> specimen >> date >> result ) )
{
... do something with result ...
results.push_back( result );
}
可以使用flex和bison:
http://www.mactech.com/articles/mactech/Vol.16/16.07/UsingFlexandBison/index.html Boost::正则表达式或
下面是我最近在Boost::regex 中做的一个例子https://github.com/homer6/import-geoip-datatypedef std::string specimen;
typedef std::string date;
typedef std::pair<specimen, date> sample;
std::map<sample, double> data;
void parse(std::istream& in) {
sample t;
double result
in.ignore(1024, 'n'); //skip the title line
while(in >> t.first>> t.second>> result)
data[t] = result;
}
定义如何读取和解析文件中的一行
#include <fstream>
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>
struct Data
{
double value;
operator double() const {return value;}
friend std::istream& operator>>(std::istream& stream, Data& d)
{
static std::string specimen; // Assume specimen has no spaces it in.
static std::string date; // Treat the date as a string as it probably has '/'
std::string line;
// Read and process each line independently (hopefully compensating for errors).
std::getline(stream, line);
std::stringstream linestream(line);
// Read and ingore the first two items. Then save the value.
linestream >> specimen >> date >> d.value;
return stream;
}
};
现在只需将文件读入vector。
int main()
{
std::ifstream file("data.file");
std::vector<double> data;
// Ignore the header line.
file.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
// Copy the data from the file into the vector.
std::copy(std::istream_iterator<Data>(file),
std::istream_iterator<Data>(),
std::back_inserter(data)
);
}
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 一种在C++中读取TXT配置文件的简单方法
- 无法打开.txt文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 我可以读取静态对象中的文件.txt吗?C++
- C++-需要读取存储在文件(.txt)中的时间戳并正确检索
- 具有文件.txt的 C++ 中的设置
- 如何在 CMakeList 中包含 h/hpp 头文件.txt而不是 cpp 或其他 hpp 文件
- 使用函数读取文件.txt中的矩阵
- 任何人都知道如何解决尝试将从MySQL数据库返回的行打印到文本文件(.txt)中的C++
- 读取文件.txt C
- 为什么我的方法不从文件.txt中读取float类型
- 如何读取名称(仅文件.txt)作为参数传递的文件(在任何目录中)?C++
- 读取文件".txt"并将每行的数据分配给循环列表中的新节点C++
- 如何用C++将字符串文件Txt解析成数组
- 如何在c++中读取和编辑文件txt
- 从文件.txt读取字符串数组并使用它来玩康威的生命游戏
- 导入文件txt时出错
- 如何仅读取文件.txt中的数字