简单点可以这么写
#include
#include
#include
using namespace std;
struct people
{
string name;
int age;
string id;
}p[20];
int main()
{
int n = 0;
ifstream in("a.txt", ios::in);
if(!in.is_open())
{
cout << "Error: opening file fail" << endl;
exit(1);
}
while(!in.eof() && n < 20)
{
in >> p[n].name >> p[n].age >> p[n].id;
n++;
}
//test
for (int i = 0; i < n; ++i)
cout << "name:" << p[i].name << " age:" << p[i].age << " id:" << p[i].id << endl;
in.close();
return 0;
}
代码片段如下:
ifstream ifile("文件名");
int i=0;
if(ifile!=0)
{
while(ifile.eof()==false)
{
ifile>>p[i].name>>p[i].age>>p[i].id;
i++;
}
}
ifile.close();