C++读入浮点数矩阵

描述

假如有这样的一个矩阵,我们要读入
C++读入浮点数矩阵_第1张图片

将程序编译为a.exe,运行。
输出的第一个方块,是读入的字符串。
第二个方块,是转成double矩阵后的输出。

C++读入浮点数矩阵_第2张图片

代码

#include 
#include 
#include 
#include 
#include 

using namespace std;

int main() {
    vector<double> temp_line;
    vector<vector<double>> Vec_Dti;
    string line;
    ifstream in("xxx.txt");  //读入文件

    // 匹配原则,这里匹配整数、小数、指数形式小数
    /* 用[0-9] 代替 参考博客里的[:digit:],不然会有莫名奇妙的坑,识别不了整数*/ 
    regex pat_regex("[-|+]?[0-9]*[.[0-9]+]?[[E|e][+|-]?[0-9]+]?]");  

    // cout << "这是读入字符矩阵后的数据:" << endl;
    while(getline(in, line)) {  //按行读取
        for (sregex_iterator it(line.begin(), line.end(), pat_regex), end_it; it != end_it; ++it) {  //表达式匹配,匹配一行中所有满足条件的字符
            cout << it->str() << " ";  //输出匹配成功的数据
            //temp_line.push_back(stoi(it->str()));  //将数据转化为int型并存入一维vector中
            temp_line.push_back(stod(it->str()));  //将数据转化为int型并存入一维vector中
        }
        cout << endl;
        Vec_Dti.push_back(temp_line);  //保存所有数据
        temp_line.clear();
    }
    cout << endl << endl;

    // cout << "这是转成浮点数矩阵后的数据:" << endl;
    for(auto i : Vec_Dti) {  //输出存入vector后的数据
        for(auto j : i) {
            cout << j << " ";
        }
        cout << endl;
    }

    return 0;
}

参考

参考了这篇博客:https://blog.csdn.net/liu798675179/article/details/77899543
但他只能读入整数,在其基础上实现了读入浮点数矩阵,鸣谢!

你可能感兴趣的:(C++,好玩东西)