c++ - 通过 C++ 解析 csv

标签 c++ parsing csv

晚上好,我遇到了以下问题。我正在像这样解析 csv 文件:

entry1;entry2;entry3
entry4;entry5;entry6
;;

我以这种方式获取条目:

stringstream iss;
while(getline(file, string) {
iss << line;
     while(getline(iss, entry, ';') {
     /do something
     }
}

但是我在最后一行 (;;) 中遇到了问题,我只读取了 2 个条目,我需要读取第三个空白条目。我该怎么做?

最佳答案

首先,我要指出代码中的一个问题,您的iss在读取第一行然后调用while(getline(iss, entry, '; ')),因此在阅读完每一行后,您需要重置 stringstream。它处于失败状态的原因是在调用 std:getline(iss, entry, ';')) 之后到达了文件末尾。

对于你的问题,一个简单的选择是简单地检查是否有任何内容被读入entry,例如:

stringstream iss;
while(getline(file, line)) {
iss << line; // This line will fail if iss is in fail state
entry = ""; // Clear contents of entry
     while(getline(iss, entry, ';')) {
         // Do something
     }
     if(entry == "") // If this is true, nothing was read into entry
     { 
         // Nothing was read into entry so do something
         // This doesn't handle other cases though, so you need to think
         // about the logic for that
     }
     iss.clear(); // <-- Need to reset stream after each line
}

关于c++ - 通过 C++ 解析 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15328316/

相关文章:

php - 处理变量中的敏感信息,使用后上传

php - SQL CSV 文件 - 跳过特定列号之后的所有列

Python:比较两组并将结果写入第三组

c++ - 从文本文件中读取行并将字符串放入 vector 中?

c++ - 这段 OpenCV 代码是在 GPU 上运行还是在 CPU 上运行?

json - 为什么 GitHub API 不返回存储库的所有分支?

Perl 输出到 CSV 文件

c++ - While循环中的C++ cin输入验证

c++ - 这个 C++ 功能的名称是什么?

java - Jackson 可以解析不同行具有不同架构的 CSV 文件吗?