如何将csv文件数据读取到数组中? [英] How to read a csv file data into an array?

查看:410
本文介绍了如何将csv文件数据读取到数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式如下的CSV文件:

I have a CSV file formatted as below:

1,50,a,46,50,b
2, 20,s,56,30,f
3,35,b,5,67,s
...

如何将其转换为2D数组以便可以进行一些计算?

How can I turn that to a 2D array so that I could do some calculations?

void Core::parseCSV(){
    std::ifstream  data("test.csv");
    std::string line;
    while(std::getline(data,line))
    {
        std::stringstream lineStream(line);
        std::string cell;
        while(std::getline(lineStream,cell,','))
        {
            //not sure how to create the 2d array here
        }
    }
};


推荐答案

尝试一下,

void Core::parseCSV()
{
    std::ifstream  data("test.csv");
    std::string line;
    std::vector<std::vector<std::string> > parsedCsv;
    while(std::getline(data,line))
    {
        std::stringstream lineStream(line);
        std::string cell;
        std::vector<std::string> parsedRow;
        while(std::getline(lineStream,cell,','))
        {
            parsedRow.push_back(cell);
        }

        parsedCsv.push_back(parsedRow);
    }
};

这篇关于如何将csv文件数据读取到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆