c++ - 如何获取 CSV 文件的列?

标签 c++ csv

我正在尝试获取 CSV 文件的最后一列。我尝试使用 getline 和 stringstream 但它只获取最后一列

stringstream lineStream(line);
    string bit;

    while (getline(inputFile, line))
    {


        stringstream lineStream(line);
        bit = "";

        getline(lineStream, bit, ',');
        getline(lineStream, bit, '\n');
        getline(inputFile, line);
        stringVector.push_back(bit);
    }

我的 CSV 文件:

5.1,3.5,1.4,0.2,no
4.9,3.0,1.4,0.2,yes
4.7,3.2,1.3,0.2,no
4.6,3.1,1.5,0.2,yes
5.0,3.6,1.4,0.2,no
5.4,3.9,1.7,0.4,yes

最佳答案

可能最简单的方法是使用 std::string::rfind如下:

while (std::getline(inputFile, line))
{
    // Find position after last comma, extract the string following it and
    // add to the vector.  If no comma found and non-empty line, treat as
    // special case and add that too.
    std::string::size_type pos = line.rfind(',');
    if (pos != std::string::npos)
        stringVector.push_back(line.substr(pos + 1));
    else if (!line.empty())
        stringVector.push_back(line);
}

关于c++ - 如何获取 CSV 文件的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53386287/

相关文章:

java - 改进从 Java 中的文本文件中提取数据

python - 添加 future 日期以绘制趋势线

c++ - 优化算法以找到满足特定属性的六位数字的数量

c++ - 如何寻址使用 36 位映射的 IO?

c++ - 通过类的 const 引用传递

python - 写入 csv 中的多列

python - 使用 Pandas 数据框合并 CSV

c++ - 类 Python C++ 装饰器

c++ - MPI Allgatherv 函数出现问题

postgresql - 将 CSV 文件导入 PostgreSQL