- 将几行txt内带空格的数字分别输入到vector容器内:
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<fstream>
using namespace std;
void main() {
string str;
vector<float>s;
ifstream fin("123.txt");
while(getline(fin,str))
{
float i;
stringstream ss(str);
//ss<<str;
while (ss>>i)
{
s.push_back(i);
cout << i << " ";
}
cout << endl;
}
getchar();
}
2. 将txt文件内输入到二维数组:
12 23 23
43 44 55
23 45 54
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<fstream>
using namespace std;
void main() {
float a[3][3]{ {0} };
string str;
vector<float>s;
ifstream fin("123.txt");
int k = 0;
while(getline(fin,str))
{
int x = 0;
float i;
stringstream ss(str);
while (ss>>i)
{
a[k][x]=i;
cout << i << " ";
x++;
}
k++;
cout << endl;
}
for (int i = 0;i < 3;i++) {
for (int j = 0;j < 3;j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
getchar();
}