最近在做文件读取的工作,因此将学习到的文件读取的代码分享一下:
本代码的作用是读取文件中的矩阵。
执行下面代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <stdio.h>
using namespace std;
int main(int argc, char* argv[])
{
std::string feature; //存储读取的每行数据
float feat_onePoint; //存储每行按空格分开的每一个float数据
std::vector<float> lines; //存储每行数据
std::vector<vector<float>> adv; //存储所有数据
adv.clear();
for (int i = 0; i < argc; i++)
{
if (strcmp(argv[i], "-x") == 0) {
while (i + 1 < argc && argv[i + 1][0] != '-') {
std::ifstream mat(argv[++i]);
while (mat.good()) {
getline(mat, feature); //一次读取一行数据
stringstream stringin(feature); //使用串流实现对string的输入输出操作
lines.clear();
while (stringin >> feat_onePoint) { //按空格一次读取一个数据存入feat_onePoint
lines.push_back(feat_onePoint); //存储每行按空格分开的数据
}
adv.push_back(lines); //存储所有数据
if (!mat.good()) break;
}
for (int i = 0 ; i < adv.size() ;i++)
{for (int j = 0 ; j < lines.size() ;j++)
cout << adv[i][j] << endl;}//输出每个元素,用于你检验是否读对了哦
mat.close();
}
}else
{
cout << i << "reading file failed" << endl;
}
}
}
首先在cmd中对此.cpp文件进行编译cl argc.cpp
再输入argc.exe -x 你的txt文件的地址
就可以读入文件啦!