C++读取txt中的矩阵数据并存入vector中

C++读取txt中的矩阵数据并存入vector中

每种矩阵数据都有他的独特性质,比如有的全是整数,有的全是小数,也有的既有小数还有整数,还有的是负数,这些数字难以用指针对字符串操作来读取,但是用正则表达式就很好处理,下面我就以正则表达式处理文本数据中的整数来示例。

假设有如下数据:

0	9	13	3	0	0	40
0	0	22	0	12	0	0
0	2	0	6	13	0	0
0	0	0	0	0	0	3
0	0	0	0	0	0	0
0	0	0	0	0	0	0
0	0	0	0	0	3	0
0	0	0	0	53	2	2
20	0	4	0	6	0	0
0	0	2	0	0	25	0
9	0	2	19	0	0	0
42	0	0	0	30	0	3
0	0	6	9	5	0	0
0	0	0	0	0	0	0
0	0	2	0	0	0	0
0	0	0	0	0	0	0

数据之间以空格或者Tab来隔开。

源代码:

#include <iostream>
#include <fstream>
#include <regex>
#include <string>
#include <vector>

using namespace std;

int main() {
	vector<int> temp_line;
	vector<vector<int>> Vec_Dti;
	string line;
	ifstream in("xxx.txt");  //读入文件
	regex pat_regex("[[:digit:]]+");  //匹配原则,这里代表一个或多个数字

	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中
		}
		cout << endl;
		Vec_Dti.push_back(temp_line);  //保存所有数据
		temp_line.clear();
	}
	cout << endl << endl;

	for(auto i : Vec_Dti) {  //输出存入vector后的数据
		for(auto j : i) {
			cout << j << " ";
		}
		cout << endl;
	}
	
	return 0;
}

输出结果:
第一个块为匹配数据,第二个快为存入vector后的数据。
结果

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值