使用C ++解析文本文件 [英] Parsing through text file with C++

查看:130
本文介绍了使用C ++解析文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出从文本文件中读取数字并将这些数字设置为变量的最佳方法.我遇到了麻烦,因为将有多个文本文件将测试我的代码,并且它们的长度和大小都不同.一个示例测试如下所示:

I am trying to figure out the best way to read in numbers from a text file and set these numbers to variables. I am having trouble because there will be multiple text files that will be testing my code and they are all of different lengths and sizes. A sample test one looks like this:

0 (1,3) (3,5)
1 (2,6)
2 (4,2)
3 (1,1) (2,4) (4,6)
4 (0,3) (2,7)

其中第一个数字表示图形上的顶点,坐标中的第一个数字是有向图中指向的顶点,第二个数字是边的权重.我尝试做getline并将其放入数组,但是在某些测试案例中可能有100个坐标,而且我不确定如何指定数组大小.我也无法通过括号和逗号来解析,并且不确定如何用文本文件中的正确数字初始化变量.

Where the first number represents a vertex on a graph, the first number in a coordinate is the vertex it is going towards in a directed graph, and the second number is the weight of the edge. I tried doing getline and putting it into arrays but in certain test cases there could be 100 coordinates and I am not sure how to specify array size. I am also having trouble parsing through the parenthesis and comma and am not sure how to initialize the variables with the correct number from the text file.

推荐答案

我会使用以下内容:

#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>

struct coordinate
{
    int vertex;
    int weight;
};

struct vertex_set
{
    int vertex;
    std::vector<coordinate> coordinates;
};

std::istream& operator>>(std::istream &in, coordinate &out)
{
    char ch1, ch2, ch3;
    if (in >> ch1 >> out.to_vertex >> ch2 >> out.weight >> ch3)
    {
        if ((ch1 != '(') || (ch2 != ',') || (ch3 != ')'))
            in.setstate(std::ios_base::failbit);
    }
    return in;
}

std::istream& operator>>(std::istream &in, std::vector<coordinate> &out)
{
    out.clear();
    coordinate coord;
    while (in >> coord)
        out.push_back(coord);
    return in;
}

std::istream& operator>>(std::istream &in, vertex_set &out)
{
    return in >> out.vertex >> out.coordinates;
}

std::ifstream f("file.txt");
std::string line;

while (std::getline(f, line))
{
    vertex_set vs;
    if (std::istringstream(line) >> vs)
    {
        // use vs.vertex and vs.coordinates as needed... 
    }
}

这篇关于使用C ++解析文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆