【发布时间】:2021-09-25 21:49:16
【问题描述】:
我一直在尝试将文本文件读入链接列表。我面临的唯一问题是它不会读取所有条目。
我的学生课:
class Student // Student class which hold student data
{
private:
char Name[15];
char Roll_no[8];
int Serial_no, FSC_marks, Entry_test_marks;
public:
void Print() // Print student data
{
cout << "\n" << Serial_no << "\t"<< Roll_no << " " << Name << "\t" << FSC_marks << "\t\t" << Entry_test_marks << endl;
}
void Read(fstream &infile)
{
infile >> Serial_no;
infile >> Roll_no ;
infile.get(Name,15);
infile >> FSC_marks >> Entry_test_marks;
}
}
链表类
class LinkList // Linked List
{
struct Node // structure for Node containing Object of Student class
{
Student info;
Node* link;
};
Node* head;
public:
Linklist() // default constructor
{
head = NULL;
}
};
打印功能如下:
void LinkList::print() // Prints List of Students
{
Node* temp = head;
if(temp != NULL)
{
while(temp != NULL)
{
temp->info.Print();
temp = temp->link;
}
cout<<endl;
}
}
阅读功能如下:
void LinkList::Readfromfile()
{
fstream File;
File.open("Lab_15.txt" , ios::in);
File.seekg(40);
while(File)
{
Node* newnode = new Node();
newnode->info.Read(File);
newnode->link = NULL;
if(head == NULL)
{
head = newnode;
}
else
{
Node* temp = head;
while(temp->link != NULL)
{
temp = temp->link;
}
temp->link = newnode;
}
}
}
文本文件如下所示:
Serial_No Roll_No Name F.Sc Entry_Test
1 19I-0777 Jame#s moriarty777 70
2 19I-0789 Sherlock 734 80
3 19I-0860 Holmes 843 88
4 19I-0884 Dave Bautista 732 54
6 20I-1003 Barry Allen# 712 32
7 20I-1004 Clark kent 632 15
8 20I-1015 Adam 658 67
9 20I-1034 Ahmad hussain 734 55
10 20I-1041 Bill ga#tes 811 98
11 20I-1054 Trump 888 45
13 20I-1057 Donald duck 576 67
14 20I-1903 Faiza#n Shahid 789 34
15 20I-1904 Umair Shahid 567 55
16 20I-1909 Abdullah 123 67
17 20I-1915 Ali 300 45
在原始文本文件中,我有大约 20 个条目,但我的代码只读取了大约 13 个。我在这里做错了什么?
【问题讨论】:
-
您实际上可以将 head 替换为新节点并将其指向旧节点。或者,如果您关心订单,请跟踪
tail,这样您就不必每次都遍历整个列表。 -
代码是在读取前 13 行时停止,还是在打印前 13 行后停止?
-
另外,您不要在每个字符数组(即
Student::Name和Student::Roll_no)的末尾为null 字符 留出空间,这可能会导致问题。文件中的第 14 行是什么?您是否尝试在读取文件时打印列表的内容?既然只有20行,你能把它的全部内容贴出来吗?我认为文件的标题不是 40 个字符长。 -
@gthanop 代码只读取前 13 行。如果我在阅读文件时打印文件,输出是相同的。增加 Roll No 的大小没有任何改变,但是增加 Name 的大小导致只打印了大约 7 个条目。我已经更新了文本文件。 (名称中还有一些“#”,我需要删除它们,我可以搜索字符,但我应该如何从单词中删除/删除特定字符)
标签: c++ class linked-list file-handling singly-linked-list