用c++解析TXT文件

parsing a txt file in c++

本文关键字:文件 TXT 解析 c++      更新时间:2023-10-16

你好,我是从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-data

typedef 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)
             );
}