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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xiangxianghehe/article/details/100709011

需要解析的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;
}

猜你喜欢

转载自blog.csdn.net/xiangxianghehe/article/details/100709011