首页 > 解决方案 > 如何在 C++ 中正确解析 CSV 文件?

问题描述

我有一个 CSV 文件,其内容类似于:

1,2,3,4,5
"f[0, 0] + f[0, 1]",5,10,0,2

我意识到 CSV 文件中的引用对于 CSV 文件并不完全“真实”;但是,这是给我的格式。引号中的函数旨在充当对 CSV 文件中数字的引用。例如,[0, 0] 表示 1,类似于 2D 数组的工作方式。[0, 1] 表示 2,因此 1 + 2 = 3。我的评估工作得很好,我只需要一种方法来解析这些行。

使用我现在拥有的代码,它用逗号分割文件,但是当它到达“f [0, 0] + f [0, 1]”时,它将它们分成:

"f[0
0] + f[0
 1]"

因为有逗号。

这是我目前必须在 CSV 文件中读取的代码:

string line;
string field;

vector<vector<string>> v_array;
vector<string> v;

// fills the 2D array up
while (getline(file, line))
{
    v.clear(); // clears to add the next line
    stringstream ss(line);

    while (getline(ss, field, ',')) // this is probably the problem, but idk how to work around it
    {
        v.push_back(field);
    }

    v_array.push_back(v);
}

如果我运行我拥有的代码并逐行解析我的 CSV 文件,它将得到类似于:

1
2
3
4
5

"f[1
 1] + f[1
 2]"
5
10
0
2

基本上,如果我做对了一切,文件将如下所示:

1,2,3,4,5
3,5,10,0,2

标签: c++c++11visual-c++

解决方案


推荐阅读