C :读取csv-file被分开;和 n

C++: Read CSV-file separated by ; AND

本文关键字:读取 csv-file      更新时间:2023-10-16

对不起,如果这只是纯粹的愚蠢,但我遇到了通过C 的文件阅读问题。这是我想阅读的CSV数据:

5;1;0;3;3;5;5;3;3;3;3;2;3;3;0
5;1;0;3;3;5;0;3;3;3;3;2;0;0;3
5;1;1;3;3;0;0;0;0;3;5;2;3;3;3
0;3;5;5;0;2;0;3;3;0;5;1;1;0;0
0;0;3;5;5;2;0;0;0;0;5;5;1;1;0
0;0;0;0;5;2;0;0;0;0;0;5;5;1;0
;;;;;;;;;;;;;;
Code;Bezeichnung;Kosten;;;;;;;;;;;;
0;Ebene;6;;;;;;;;;;;;
1;Fluss;10; (begrenzt nutzbar);;;;;;;;;;;
2;Weg;2;;;;;;;;;;;;
3;Wald;8;;;;;;;;;;;;
4;Brücke;5;;;;;;;;;;;;
5;Felswand;12;;;;;;;;;;;;

在这里,我想读取第一个值(由;;; ;;)并将其存储在2维数组中。如果它完全被';'完全分开,那不是问题。但是如果使用

while (getline(csvread, s, ';'))
{
[...]
}

我得到这样的信息: {5}{1}{0}{3}{3}{5}{5}{3}{3}{3}{3}{2}{3}{3}{0n5}{1}因此,它基本上保存了新线,并不认为它是定界符。

那么,即使您有两个分隔符,也可以选择使用getline吗?还是我完全离开?我还考虑过按行读取该字符串,添加a;到字符串并将其重写在文件中,以便使用getline使用;。但这不能认真是最好的选择,对吗?

您应该分别进行'n'';'分开:

// here split into lines by 'n'
while (getline(csvread, line, 'n'))
{
    // in here, split line by ;
    std::vector<std::string> elems;
    boost::split(elems, line, boost::is_any_of(";"));
    // do something with elems
}

您可以使用:

的分裂函数
std::vector<std::string> split(const std::string& source, const std::string& delimiter){
    std::vector<std::string> result;
    size_t last = 0;
    size_t next = 0;
    while ((next = source.find(delimiter, last)) != std::string::npos){ 
        result.push_back(source.substr(last, next - last));
        last = next + delimiter.length();
    } 
    result.push_back(source.substr(last));
    return result;
}

现在简单:

std::vector<std::vector<std::string>> parsedCSV;
while (getline(csvread, s, 'n'))
{
parsedCSV.push_back(split(s,";"));
}

我最近也必须读取CSV-DATA,然后偶然发现了相同的'问题'。这是我所做的:

  1. getline(csvread, s)一起阅读,这将读取到第一个newline。
  2. ;的每一个情况下,都将字符串分开,我使用此stackoverflow答案作为拆分字符串的灵感,代码也在下面列出。

我不太在意表现,因为我只需要一次运行此程序,我不会对此解决方案的速度发表评论。

祝你好运!

编辑:显然提供了拆分字符串的代码,可能更清洁,如果要避免提升,请考虑以下代码。


#include <string>
#include <sstream>
#include <vector>
// source: https://stackoverflow.com/a/236803/4841248
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}

尝试这样的东西:

std::vector<std::string> cells;
while (getline(csvread, s) ){
   boost::split(cells, s, boost::is_any_of(";"));
   ....
}