如何处理csv文件输入流,我需要将文件的每一行中的数据划分为6个不同的变量(类型字符串和int)

How to deal with csv file input stream where I need to divide the data in each row of the file into 6 different varaibles (types string and int)

本文关键字:文件 6个 数据划分 一行 变量 int 字符串 类型 输入流 csv 何处理      更新时间:2023-10-16

我有一个数据用逗号分隔的CSV文件。文件看起来像这样:

1998,MALE,United States,45,566
1993,FEMALE,......

我将有一个类ROW的向量,数据文件中的每一行都将存储在那里。我的ROW有5个变量,我需要将它们分开,这样我就可以使用设置函数到row.set(year,sex, country, score, result)

知道如何读取数据吗?

从我被告知我应该尽量避免getline。我不想将string s转换为int s。

任何想法?

我可能会从一个小操作符开始,以验证字符串是否存在(否则会忽略),就像这样:

std::istream &operator>>(std::istream &is, char const *pat) {
    char ch;
    while (isspace(static_cast<unsigned char>(is.peek())))
        is.get(ch);
    while (*pat && is && *pat == is.peek() && is.get(ch)) {
        ++pat;
    }
    // if we didn't reach the end of the pattern, matching failed (mismatch, premature EOF, etc.)
    if (*pat) {
        is.setstate(std::ios::failbit);
    }
    return is;
}

我们可以使用它来验证需要逗号的地方是否存在,但忽略它们则相当轻松。然后,我为ROW类型重载operator>>以适当地读取数据:

class ROW { 
    int year;
    enum { MALE, FEMALE} sex;
    std::string country;
    int foo;
    int bar;
    friend std::istream &operator>>(std::istream &is, ROW &r) { 
        is >> r.year >> ",";
        std::string s;
        is >> s >> ",";
        if (s == "MALE")
            r.sex = MALE;
        else if (s == "FEMALE")
            r.sex = FEMALE;
        else
            error("bad sex");
        std::getline(is, r.country, ',');
        return is >> r.foo >> "," >> r.bar;
    }
};
从这里,我们可以相当直接地创建一个向量:
// Open the file
std::ifstream in("data.txt");
// Read all the data
std::vector<ROW> rows { std::istream_iterator<ROW>(in), {}};