参考链接
最近需要用到读取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;
}```