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

标签 c++ csv for-loop iterator

我正在关注 Loki Astari 在

上的解决方案代码

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

我如何在主函数中编写一个迭代器来计算 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

最佳答案

如果您通读 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

关于c++ - 使用 C++ 计算 csv 中列数的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42819204/

相关文章:

c++ - Valgrind 'uninitialised value' 依赖不引用我的代码

c++ - 以纳秒为单位存储时间戳 C++

python - Pandas 无法使用 pandas 读取带有额外引号字符的 CSV 文件

iOS:for循环中对象的属性为空?

r - 有没有办法使用 dplyr 根据除以另一列的 group_by 来创建新列?

c++ - MSVC 和 GCC 之间的 vector 行为不同

c++ - 如何在 C++ 中从 bytearray 中提取字节时交换 64 位整数?

matlab - 将来自网络源的逗号分隔的.csv数据存储到matlab中的矩阵中

javascript - 来自 CSV 的 D3.js 树形布局

python - 在 python 中的循环中编写循环的更简洁的方法