c++把txt解析后传入二维数组

需要解析的txt文件内容如下所示:

-1.0727, 2.00009, 376.7367, -8773.73,  
-2.8978, 0.8940, 738.4082, -0.938,

特点是每个数字后都有一个逗号+空格,最后一个数字也是,但是数字是二维数组的存储形式。解析代码如下:

#include <iostream>
#include <fstream>
#include <vector>

int main()
{
    //double array_txt[2][4]={0};
	std::string filename = "file.txt";
    //读取txt文件
    std::ifstream infile;
    infile.open(filename.c_str(), ios::in);
    if (!infile)
    {
        std::cout << "fail to open the source file " << std::endl;
        exit(1);
    }
    string csvLine;
    vector<double> vec;
    // read every line from the stream
    while (getline(infile, csvLine))
    {
        istringstream csvStream(csvLine);
        vector<double> csvColumn;
        string csvElement;
        // read every element from the line that is seperated by commas
        // and put it into the vector or strings
        while (getline(csvStream, csvElement, ' '))
        {
            csvElement.pop_back();
            vec.push_back(std::stod(csvElement));
        }
    }

    for (int m = 0; m < 2; m++)
    {
        for (int n = 0; n < 4 n++)
        {
            array_txt[m][n] = vec[m * 2 + n];
            std::cout << array_txt[m][n] << std::endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值