关于c++类链表读取TXT文件的问题
读取TXT文件不能读取最后一行,而且程序还会崩溃,这是怎么回事啊?代码如下:#include<iostream>#include<fstream>#include<str...
读取TXT文件不能读取最后一行,而且程序还会崩溃,这是怎么回事啊?
代码如下:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class student
{
public:
int num;
string name;
int score;
student *next;
void creatList(student *&sPeople)
{
ifstream readFile("F:\\student.txt", ios::in);
student *s, *p = NULL;
s = new student;
readFile >> s->num >> s->name >> s->score;
while (!readFile.eof())
{
if (sPeople == NULL)
sPeople = s;
else
p->next = s;
p = s;
s = new student;
readFile >> s->num >> s->name >> s->score;
}
p->next = NULL;
delete s;
return;
}
void showList(student *sPeople)
{
while (sPeople)
{
cout << "学号:" << sPeople->num << "\t姓名:" << sPeople->name << "\t分数:" << sPeople->score << endl;
sPeople = sPeople->next;
}
}
};
int main()
{
student *sPeople = NULL;
sPeople->creatList(sPeople);
sPeople->showList(sPeople);
} 展开
代码如下:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class student
{
public:
int num;
string name;
int score;
student *next;
void creatList(student *&sPeople)
{
ifstream readFile("F:\\student.txt", ios::in);
student *s, *p = NULL;
s = new student;
readFile >> s->num >> s->name >> s->score;
while (!readFile.eof())
{
if (sPeople == NULL)
sPeople = s;
else
p->next = s;
p = s;
s = new student;
readFile >> s->num >> s->name >> s->score;
}
p->next = NULL;
delete s;
return;
}
void showList(student *sPeople)
{
while (sPeople)
{
cout << "学号:" << sPeople->num << "\t姓名:" << sPeople->name << "\t分数:" << sPeople->score << endl;
sPeople = sPeople->next;
}
}
};
int main()
{
student *sPeople = NULL;
sPeople->creatList(sPeople);
sPeople->showList(sPeople);
} 展开
1个回答
展开全部
createlist函数改成这样
void creatList(student *&sPeople)
{
ifstream readFile("F:\\student.txt", ios::in);
student *s, *p = NULL;
while (!readFile.eof())
{
s = new student;
readFile >> s->num >> s->name >> s->score;
if (sPeople == NULL)
sPeople = s;
else
p->next = s;
p = s;
}
p->next = NULL;
return;
}
最后一行读不到是因为读取最后一行时
s = new student;
readFile >> s->num >> s->name >> s->score;
然后循环结束,你一个delete s,把最后一行的数据删除了
void creatList(student *&sPeople)
{
ifstream readFile("F:\\student.txt", ios::in);
student *s, *p = NULL;
while (!readFile.eof())
{
s = new student;
readFile >> s->num >> s->name >> s->score;
if (sPeople == NULL)
sPeople = s;
else
p->next = s;
p = s;
}
p->next = NULL;
return;
}
最后一行读不到是因为读取最后一行时
s = new student;
readFile >> s->num >> s->name >> s->score;
然后循环结束,你一个delete s,把最后一行的数据删除了
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询