读取文件和存储数据时出现链表错误c
我的项目是读取包含学生姓名的.txt文件,我必须输入他们的分数(最多5个输入),并且姓名应该是链接列表,如附件图片所示 我面临的一个问题是,当我试图输入第三名学生的分数数据时,程序会崩溃,我认为这是内存溢出的问题,但我不知道如何删除任何部分来释放内存,因为所有的链表都是用来指向彼此的 如果有人能告诉我可能有什么问题,我将不胜感激。对不起,我的英语很差,非常感谢 我的代码和txt文件如下读取文件和存储数据时出现链表错误c,c,linked-list,C,Linked List,我的项目是读取包含学生姓名的.txt文件,我必须输入他们的分数(最多5个输入),并且姓名应该是链接列表,如附件图片所示 我面临的一个问题是,当我试图输入第三名学生的分数数据时,程序会崩溃,我认为这是内存溢出的问题,但我不知道如何删除任何部分来释放内存,因为所有的链表都是用来指向彼此的 如果有人能告诉我可能有什么问题,我将不胜感激。对不起,我的英语很差,非常感谢 我的代码和txt文件如下 #include <iostream> #include <stdio.h> #in
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct nodeName {
char *name;
struct nodeName *linkToName;
struct nodeScore *linkToScore;
};
struct nodeScore {
int score;
struct nodeScore *linkNextScore;
};
struct nodeName *insertName(struct nodeName *ptr, char *nameIn);
struct nodeName *insertScore(struct nodeName *ptr);
void displayList(struct nodeName *ptr);
struct nodeName *insertName(struct nodeName *ptr, char *nameIn) {
struct nodeName *n = (struct nodeName *)malloc(sizeof(struct nodeName));
int counter = 0;
int scoreTemp;
char checkInt;
char *tag;
struct nodeScore *tempS;
tag = nameIn;
n->name = tag;
while (counter < 5) {
struct nodeScore *s = (struct nodeScore *)malloc(sizeof(struct nodeScore));
counter++;
printf("Enter %d Score of %s:", counter, tag);
if (scanf("%d%c", &scoreTemp, &checkInt) != 2 || checkInt == 'n') {
printf("\nEnd saving %s's score.\n", tag);
break;
}
s->score = scoreTemp;
if (n->linkToScore == NULL) //for the first link to node of score.
n->linkToScore = s;
else
tempS->linkNextScore = s;
s->linkNextScore = NULL;
tempS = s;
}
ptr = n;
return ptr;
}
int main() {
FILE *nameF = fopen("HW5_26.txt", "r");
char input[512];
char *SingleName;
struct nodeName *p1, *temp;
int testN1 = 0;
while (fgets(input, 512, nameF)) { //get file line by line
SingleName = strtok(input, " "); //if 'space' or 'New line', save as a single name.
printf("\n");
printf("Name# %d = %s\n", ++testN1, SingleName);
printf("\n");
p1 = insertName(p1, SingleName);
temp = p1;
while (SingleName != NULL) {
SingleName = strtok(NULL, " "); //put n name into SingleName
if (SingleName != NULL) {
printf("___________________________\n\n");
printf("Name# %d = %s\n", ++testN1, SingleName);
printf("\n");
p1 = insertName(p1, SingleName);
temp->linkToName = p1;
temp = p1;
}
}
}
return 0;
}
代码中存在主要的设计问题:
- 您应该允许使用多个名称:
是两个单词。名称文件每行应包含一个全名。使用Albert Einstein
阅读它,并使用fgets()
str[strcspn(str,“\n”)]='\0'删除尾随的换行符代码>
- 您应该将所有标记作为一行读取,并使用
解析它们。当由strtol()
更新的指针未移动时,您已读取所有标记strtol()
- 插入姓名的代码不会将节点附加到
列表中学生
- 函数
应使用insertName()
或等效项复制字符串。按照编码,所有节点的名称都指向strdup()
函数中相同缓冲区的某个部分,该部分被对main
的每次调用所覆盖fgets()
- 您声明了一个
函数,但未使用它。为了清晰起见,最好将代码移动到单独的函数insertScore
- 您应该检查
和fopen
的返回值,以便优雅地处理错误malloc
- 您可以使用
删除typedef
关键字,使代码更易于阅读struct
scanf()
有一些限制。从strtok开始,continue是一个很好的函数。
Albert Steve David Mike
Andrew Joanne Chris Fred
Dennis Leo Fred Frances
Dave Hua Sarah