提问者:小点点

如何读取带有多个分隔符的文本文件?


我有一个源代码,它读取文本文件并存储到一个元组类型的向量中:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <tuple>
#include <algorithm>

typedef std::vector<std::tuple<int, int, double>> VectorTuple;

VectorTuple Readfile(std::string filename)
{
    std::ifstream File(filename);
    if (!File.is_open())
    {
        std::cout << "File '" << filename << "' does not exist.";
        exit(1);
    }
        
    VectorTuple data;
    std::string line;

    while (std::getline(File, line))
    {
        std::stringstream ss(line);
        int a, b; double c;
        if (ss >> a >> b >> c)
        {
            data.push_back(std::tuple<int, int, double>(a, b, c));
        }
    }

    return data;
}

int main()
{
    std::string file = "data.txt";
    auto vt = Readfile(file);
    
    for_each(vt.begin(), vt.end(), [](std::tuple<int, int, double> i){
        std::cout << std::get<0>(i) << ", " << std::get<1>(i) << ", " << std::get<2>(i) << std::endl;
    });
    
    return 0;
}

data.txt包含以下数据:

30000 | 49999 | 4
50000 | 119999 | 6.5
120000 | 279999 | 8
280000 | 499999 | 9
500000 | 999999 | 10
1000000 | 1999999 | 13
2000000 | 2499999 | 15
2500000 | 2999999 | 17.5
3000000 | 3499999 | 20
3500000 | 3999999 | 22.5
4000000 | 4499999 | 25
4500000 | 4999999 | 27.5

因此数据由空格+垂直线+空格(多重分隔符)分隔。

如何更改源代码以处理多个分隔符?

注意:如果数据仅用空格隔开,则程序可以工作。


共1个答案

匿名用户

您可以通过以下方式读取和丢弃:

std::stringstream ss(line);
int a, b; double c;
char s;
if (ss >> a >> s >> b >> s >> c)
{
    data.push_back(std::tuple<int, int, double>(a, b, c));
}