65,211
社区成员
发帖
与我相关
我的任务
分享
Node* StudentList::ReadFile(char *filename)
{
ifstream m_Ifile;
m_Ifile.open(filename,ios::in);
string line,word;
if(!m_Ifile)
{
cout<<"打开文件失败!"<<endl;
return NULL;
}
m_Ifile.seekg(0,ios_base::end); //将文件指针移动到文件尾部
if(!m_Ifile.tellg()) //文件长度为0,返回
{
cout<<"不存在任何学生信息,请添加!"<<endl;
return NULL;
}
m_Ifile.seekg(0); //将文件指定重新移动到首位置
while(!m_Ifile.eof()) //读取学生信息
{
pNew=new Node();
m_Ifile>>pNew->sID;
m_Ifile>>pNew->sName;
m_Ifile>>pNew->bSex;
m_Ifile>>pNew->Score[0];
m_Ifile>>pNew->Score[1];
if(pHead==NULL)
{
pTail=pHead=pNew;
}
else
{
pTail->pNext=pNew;
pTail=pTail->pNext;
}
pTail->pNext=NULL;
}
cout<<"加载学生信息成功!"<<endl;
return pHead;
void StudentList::ShowStudent(StudentList &list)
//setiosflags(ios::left)控制输出格式左对齐,要包含头文件<iomanip>
//setw()控制输出宽度,不足用空格添充
{
Node* p=pHead;
if(p==NULL)
{
cout<<"不存在任何学生的信息!请先添加!"<<endl;
cout<<"——————————————————————————"<<endl;
return;
}
cout<<setiosflags(ios::left)<<setw(15)<<"ID"<<setw(15)<<"Name"<<setw(15)
<<"Sex"<<setw(15)<<"English"<<setw(15)<<"Math"<<endl;
while(p!=NULL)
{
cout<<setiosflags(ios::left)<<setw(15)<<p->sID<<setw(15)<<p->sName<<setw(15)
<<p->bSex<<setw(15)<<p->Score[0]<<setw(15)<<p->Score[1]<<endl;
p=p->pNext;
while(getline(line,m_Ifile)) //读取学生信息
{
os<<line;
pNew=new Node();
os>>pNew->sID;
os>>pNew->sName;
os>>pNew->bSex;
os>>pNew->Score[0];
os>>pNew->Score[1];
if(pHead==NULL)
{
pTail=pHead=pNew;
}
else
{
pTail->pNext=pNew;
pTail=pTail->pNext;
}
pTail->pNext=NULL;
}
if(pHead==NULL)
{
pTail=pHead=pNew;
}
else
{
pTail->pNext=pNew;
pTail=pTail->pNext;
}
pTail->pNext=NULL;
有问题吧。
把while(!m_Ifile.eof()) 换成while(getline(line,m_Ifile))的形式试试
Node* StudentList::ReadFile(char *filename)
{
ifstream m_Ifile;
m_Ifile.open(filename,ios::in);
string line,word;
stringstream os;
if(!m_Ifile)
{
cout<<"打开文件失败!"<<endl;
return NULL;
}
m_Ifile.seekg(0,ios_base::end); //将文件指针移动到文件尾部
if(!m_Ifile.tellg()) //文件长度为0,返回
{
cout<<"不存在任何学生信息,请添加!"<<endl;
return NULL;
}
m_Ifile.seekg(0); //将文件指定重新移动到首位置
while(getline(line,m_Ifile)) //读取学生信息
{
os<<line;
pNew=new Node();
os>>pNew->sID;
os>>pNew->sName;
os>>pNew->bSex;
os>>pNew->Score[0];
os>>pNew->Score[1];
if(pHead==NULL)
{
pTail=pHead=pNew;
}
else
{
pTail->pNext=pNew;
pTail=pTail->pNext;
}
pTail->pNext=NULL;
}
cout<<"加载学生信息成功!"<<endl;
return pHead;
}
chin_chen 把你的char ch[156];改为string ch;你就清楚了!
string类型不会接受行尾的回车符,char数组只要是字符通入囊中!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile("test.txt"); //此文件中存有字串abc
char ch[156];
while(!infile.eof())
{
infile>>ch;
cout<<ch; //这里会输出两次abcabc, why?
}
system("pause");
return 0;
}
话不多说了,如果楼上的各位还没有理解file.eof()的精髓,看看下面间单的实例,或许对理解有帮助!
int _tmain(int argc, _TCHAR* argv[])
{
ifstream infile("c:\\1.txt"); //此文件中存有字串abc
string ch;
while(!infile.eof())
{
infile>>ch;
cout<<ch; //这里会输出两次abcabc, why?
}
return 0;
}
结合我上面说的,慢慢体会吧,自己琢磨出来的比别人讲的更利于记忆!