【发布时间】:2014-01-11 06:03:11
【问题描述】:
我有一个函数可以从文件中获取一些信息并将其放入一个结构中。我设置了一个循环(与 for 和 while 两者),条件是它一直持续到文件末尾。 但它不起作用。
void FileToStructProfessors()
{
int n;
fstream CurrentFile("professor.txt");
if (!CurrentFile)
{
cout <<"can't open file";
}
else
{
CurrentFile.seekp(5);
/*for(n=0;CurrentFile.eof();n++)
{
CurrentFile>>P1[n].FirstName;
CurrentFile>>P1[n].LastName;
CurrentFile>>P1[n].PID;
CurrentFile>>P1[n].Major;
CurrentFile>>P1[n].Level;
CurrentFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout<<P1[0].FirstName<<endl;
}*/
n=0;
while(!CurrentFile.eof())
{
CurrentFile>>P1[n].FirstName;
CurrentFile>>P1[n].LastName;
CurrentFile>>P1[n].PID;
CurrentFile>>P1[n].Major;
CurrentFile>>P1[n].Level;
CurrentFile>>P1[n].Date;
CurrentFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout<<P1[3].FirstName<<endl;
n++;
}
}
CurrentFile.close();
}
教授.txt
4
hamed
hamidi
1001
civil
associate professor
91/02/15
morteza
jafari
1005
computer
assistant professor
91/01/20
mahdi
foladi
1006
computer
professor
90/10/10
mostafa
mohammadi
1009
electronic
assistant professor
91/05/5
教授结构
struct Professors
{
string FirstName,LastName;
long long int PID;
string Major,Level,Date;
}P1[100];
【问题讨论】:
-
@user2589043 不要使用
if(!currentFile),使用if(!currentFile.fail())。 -
@user2589043 请试一试我的答案。
-
@Keeler 谢谢你,你帮了很多忙。