读取文件的最后一行并输入到链接列表时出错

Error reading last line of file and inputing into Linklist

本文关键字:输入 链接 列表 出错 一行 文件 最后 读取      更新时间:2023-10-16

所以我正在为我的类做一个作业,在这个作业中,我必须从一个文件中读取数据,并用它创建一个双链表。我已经完成了所有困难的事情,现在我遇到了一个问题,我的程序抛出了一堆随机字符,并在最后一行自杀。

这是读取数据并将其插入我的链接列表的函数。这是我的教授写的,所以坦率地说,我不是很理解。

void PropogateTheList(ifstream & f, LinkList & ML)
{
static PieCake_struct * record;
record= new PieCake_struct;
f>>record->id>>record->lname>>record->fname>>record->mi>>record->sex>>record->pORc;
while(!f.eof())
{
ML.Insert(record);
record = new PieCake_struct;
f>>record->id>>record->lname>>record->fname>>record->mi>>record->sex>>record->pORc;
}
}

以下是正在传播的数据:

1   Abay         Harege N O C
2   Adcock       Leand R F P
3   Anderson     Logan B M P
5   Bautista     Gloria A F P
10  Beckett      Dallas B F C
12  Ambrose      Bridget C F C
13  Beekmann     Marvin D M P
14  Bacaner      Tate D M C
16  Bis          Daniel F M P
18  Dale         Kaleisa G F C
19  DaCosta      Ricardo H M P
23  Adeyemo      Oluwanifemi I M C
24  Berger       Chelsea J F C
38  Daniels      Jazmyn K F P
39  Davis        Takaiyh L F C
40  DeJesus      Gabriel M M P
51  Castro       Floriana N F P
52  Chen         Justin O M C
53  Clouden      Ariel P F P
54  Conroy       Cameron Q M C
61  Contreras    Dominic R M P
62  Cooley       Kyle S M C
63  Creighton    Cara T F P
64  Cullen       William U M C
66  Blakey       Casey V M  C
67  Barbosa      Anilda W F P
83  Brecher      Benjamin X M P
84  Boulos       Alexandre Y F C
85  Barrios      Joshua Z M C
85  Bonaventura  Nash A M P
86  Bohnsack     David B M C
87  Blume        Jeffrey C M P
90  Burgman      Megan D F C
91  Bursic       Gregory E M P
92  Calvo        Sajoni F F C
93  Cannan       Austin G M  P
94  Carballo     Nicholas H M C
99  AlbarDiaz    Matias I F P

目前,我根据姓氏按字母顺序对数据进行排序,所以大约在第5行,当它试图打印出数字99(AlabraDiaz(时,它就死了。如果我用另一种方式对列表进行排序,不管最后一行数据是什么,程序总是会搞砸。任何帮助都会很棒!

更新:

因此,我尝试在插入之前实现if(!.of(((,但不幸的是,它没有任何作用。我删除了最后一个数据,从而使人Carballo。这就是我的函数打印出来的:

****** The CheeseCake Survey ****** 
Id      Last Name       First Name      MI      Sex     Pie/Cake
--      --------        ---------       --      ---     --------
2       Adcock
23      Adeyemo
12      Ambrose
3       Anderson
14      Bacaner
67      Barbosa
85      Barrios
5       Bautista
10      Beckett
13      Beekmann
24      Berger
16      Bis
66      Blakey
87      Blume
86      Bohnsack
85      Bonaventura
84      Boulos
83      Brecher
90      Burgman
91      Bursic
92      Calvo
93      Cannan
0       Carballo????NicholasA8?zL`8?zL`A8?zL`8?zL`??

如果您先从流中读取,然后检查它是否处于eof状态,并在此基础上插入元素,这不是更好吗?我在没有编译器帮助的情况下编写以下代码,在编辑框中,所以如果我犯了任何错误,我深表歉意。当然,问题来了,或者我想的是,如果你试图从f流中读取eof结果为true,会发生什么。要了解更多信息,您可以查看以下链接:为什么iostream::eof在循环条件(即`while(!stream.eof(((`(中被认为是错误的?

void PropogateTheList(ifstream & f, LinkList & ML)
{
while(!f.eof())
{
static PieCake_struct * = new PieCake_struct;
f>>record->id>>record->lname>>record->fname>>record->mi>>record->sex>>record->pORc;
if(!f.eof())
ML.Insert(record);
}
}