我正在遵循洛基·阿斯塔里的解决方案代码
如何读取和解析 C++ CSV 文件?
如何在主函数中编写迭代器来计算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_data
是一个std::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