c++从txt文件读取一个矩阵数据

#include <iostream>
#include <vector>
#include <fstream>
#include <zconf.h>
#include <string>
#include <sstream>

std::vector<std::vector<double >> readMatrixFile(const char *fileName) {

    // get current workspace path
//    char *buffer;
//    if((buffer = getcwd(NULL,0))==NULL){
//        throw std::logic_error("getcwd error");
//    }else{
//        std::cout<<buffer<<std::endl;
//        free(buffer);
//    }

    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
    {
        throw std::logic_error("read file fail");
    } else//文件存在
    {
        while (getline(fileStream, tmp, '\n'))//读取一行
        {
            std::cout<<tmp<<std::endl;
            if(count==0){
                row = std::stoi(tmp);
            }else{
                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::cout << "Hello, World!" << std::endl;
    std::vector<std::vector<double>> matrixALL = readMatrixFile("../matrix.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;
    }
    return 0;
}

txt文件格式:

5
1 2 3 4 5
5 6 7 7 6
0 1 2 2 7
5 6 6 6 8
5 6 6 6 8

 

  • 8
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值