C++读取TXT中数字矩阵的代码

参考链接
最近需要用到读取TXT中的2维数字矩阵
TXT中每一行有4个数字,对应矩阵中的一行
列数未知

类似这种

 2.50000e-01 3.50250e+02 4.25000e+01 3.46750e+02
 2.50000e-01 6.50250e+02 3.07500e+01 6.49750e+02
 2.50000e-01 1.00075e+03 2.37500e+01 9.93750e+02
 2.50000e-01 1.06325e+03 1.43250e+02 1.00925
 7.50000e-01 2.65250e+02 1.62500e+01 2.70750e+02
 7.50000e-01 3.23500e+02 4.15000e+01 3.08500e+02
 7.50000e-01 6.67250e+02 5.97500e+01 6.65750e+02
 7.50000e-01 8.91500e+02 1.46500e+02 8.56500e+02

参考了上面参考链接后,经过部分修改,
代码文件为
注意:路径目录之间为 \ \

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;


std::vector<std::vector<double >> readMatrixFile(const char* fileName) {
    std::vector<std::vector<double>> matrixALL{};
    int row = 0;
    std::ifstream fileStream;
    std::string tmp;
    int count = 0;// 行数计数器
    fileStream.open(fileName, std::ios::in);//ios::in 表示以只读的方式读取文件

    if (fileStream.fail())//文件打开失败:返回0
    {
        cout << "fail to open file" << endl;
    }
    else//文件存在
    {

        while (getline(fileStream, tmp, '\n'))//读取一行
        {
            //std::cout <<"tmp" << tmp << std::endl;
            row = 4;//每一行的数字个数为4个
            std::vector<double > tmpV{};
            std::istringstream is(tmp);
            for (int i = 0; i < row; i++) {
                std::string str_tmp;
                is >> str_tmp;
                tmpV.push_back(std::stod(str_tmp));
            }
            matrixALL.push_back(tmpV);

            count++;
        }
        fileStream.close();
    }

    return matrixALL;
}

int main() {
    std::vector<std::vector<double>> matrixALL = readMatrixFile("C:\\Users\\y50018302\\Downloads\\tea_room\\output\\sold_line_detect0.txt");
    for (int i = 0; i < matrixALL.size(); i++) {
        for (int j = 0; j < matrixALL[0].size(); ++j) {
            std::cout << matrixALL[i][j]<<" ";
        }
        std::cout << std::endl;
    }
    cout << matrixALL.size() << " " << matrixALL[1].size() << endl;
    //system("pause");
    return 0;
}```

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值