C++从txt文件读取数据保存为二维数组

比如数据这样,不管他中间的空格多少

最后保存为数组后,效果如下:

#include<iostream>
#include<fstream>
#include<sstream>
#include<vector>

using namespace std;

int main()
{
	ifstream f;
	f.open("data.txt");

	string str;
	vector<vector<int> > num;
	while(getline(f, str))
	{
		istringstream input(str);
		vector<int> tmp;
		int a;
		while(input >> a)
			tmp.push_back(a);

		num.push_back(tmp);
	}

	for(int i = 0; i < num.size(); ++i)
	{
		for(int j = 0; j < num[i].size(); ++j)
		{
			cout << num[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_22080999/article/details/82532157