迭代器使用C ++计算csv中的列数

时间:2017-03-15 19:38:38

标签: c++ csv for-loop iterator

我正在遵循Loki Astari的解决方案代码

How can I read and parse CSV files in C++?

如何在main函数中编写迭代器来计算CSV标题中的列数

int main()
{
    std::ifstream       file("plop.csv");

    for(CSVIterator loop(file); loop != CSVIterator(); ++loop)
    {
        //Instead of printing the 4th element as shown below, I want to  print all the
        //columns and thus determine the number of columns

         //std::cout << "4th Element(" << (*loop)[3] << ")\n";


    }
}

以下是我正在使用的csv文件的示例标题

cmd, id, addr, qos, len, lock, prot, burst, size, cache, user, duser, dstrb, data

我想使用迭代器或一些for循环来打印它们,并确定在这种情况下为14的列数

1 个答案:

答案 0 :(得分:1)

如果您阅读CSVIterator代码,则会使用具有以下方法的CSVRow类:

std::size_t size() const
{
    return m_data.size();
}

其中m_datastd::vector<std::string>,其中每个std::string是该行中的单个列。因此,调用CSVRow::size会返回列数。

int main()
{
    std::ifstream file("plop.csv");

    for(CSVIterator loop(file); loop != CSVIterator(); ++loop)
    {
        const auto numCols = (*loop).size();

        std::cout << "Number of Columns: " << numCols << std::endl;

        for(std::size_t i = 0; i < numCols; ++i)
        {
            // Print each column on a new line
            std::cout << (*loop)[i] << std::endl;
        }
    }
}

输入:

cmd, id, addr, qos, len, lock, prot, burst, size, cache, user, duser, dstrb, data

输出:

Number of Columns: 14
cmd
 id
 addr
 qos
 len
 lock
 prot
 burst
 size
 cache
 user
 duser
 dstrb
 data
相关问题