C++读取txt文件夹时使用数据流的形式进行读取,具体操作如下:
头文件如下
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <cassert>
using namespace std;
具体函数如下:
void Readtxt::txt_to_vectordouble(vector<vector<double>>& res, string pathname)
{
ifstream infile;
infile.open(pathname.data()); //将文件流对象与文件连接起来
assert(infile.is_open()); //若失败,则输出错误消息,并终止程序运行
vector<double> suanz;
string s;
while (getline(infile, s)) {
istringstream is(s); //将读出的一行转成数据流进行操作
double d;
while (!is.eof()) {
is >> d;
suanz.push_back(d);
}
res.push_back(suanz);
suanz.clear();
s.clear();
}
infile.close(); //关闭文件输入流
}
调用时
#include <iostream>
#include "Readtxt.h"
int main()
{
Readtxt r;
vector<vector<double>> data;
r.txt_to_vectordouble(data, "C:\\Users\\Efan\\Desktop\\data\\doubledata.txt");
for (auto a : data) {
for (auto b : a) {
cout << b << " ";
}
cout << endl;
}
}
doubledata.txt文件内容如下:
执行结果如下: