#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