经常需要用到读txt文件里的数据,总结一个模板希望以后可以直接套用。
//C++ 读txt文件
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
string filepath="111.txt";
ifstream myfile(filepath);
string temp;
vector<vector<string>> result;
vector<string> res;
while (getline(myfile, temp))
{
stringstream input(temp);
string out;
while (input >> out) {
res.push_back(out);
}
result.push_back(res);
res.clear();
}
for (int i = 0; i < result.size(); i++) {
for (int j = 0; j < result[i].size(); j++) {
cout << result[i][j]<<"\t";
if (j == result[i].size() - 1) cout << endl;
}
}
return 0;
}