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后的数据。