我正在尝试获取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/

10-16 04:47