Извлечение определенных строк из файла CSV в C ++ - PullRequest
0 голосов
/ 03 апреля 2020

Я хотел бы знать, как я могу извлечь / пропустить определенные строки, например, age == 32 или age == None из файла CSV в C ++.

Имеет ли смысл больше извлечь нужную информацию после того, как я загрузил весь CSV-файл (если память не проблема)?

РЕДАКТИРОВАТЬ : Если возможно, я хотел бы иметь чтение, печать и часть модификации.

Если возможно, я хочу использовать только STL. Содержимое моего тестового CSV-файла выглядит следующим образом:

*test.csv*

name;age;weight;height;test
Bla;32;1.2;4.3;True
Foo;43;2.2;5.3;False
Bar;None;3.8;2.4;True
Ufo;32;1.5;5.4;True

Я загружаю файл test.csv следующей программой C ++, которая выводит содержимое файла на экран:

#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
#include <fstream>
#include <sstream>

void readCSV(std::vector<std::vector<std::string> > &data, std::string filename);
void printCSV(const std::vector<std::vector<std::string>> &data);

int main(int argc, char** argv) {
    std::string file_path = "./test.csv";
    std::vector<std::vector<std::string> > data;
    readCSV(data, file_path);
    printCSV(data);
    return 0;
}

void readCSV(std::vector<std::vector<std::string> > &data, std::string filename) {
    char delimiter = ';';
    std::string line;
    std::string item;
    std::ifstream file(filename);
    while (std::getline(file, line)) {
        std::vector<std::string> row;
        std::stringstream string_stream(line);
        while (std::getline(string_stream, item, delimiter)) {
            row.push_back(item);
        }
        data.push_back(row);
    }
    file.close();
}

void printCSV(const std::vector<std::vector<std::string> > &data) {
    for (std::vector<std::string> row: data) {
        for (std::string item: row) {
            std::cout << item << ' ';
        }
        std::cout << std::endl;
    }
}

Буду очень признателен за любую помощь.

...