【发布时间】:2021-09-04 00:11:22
【问题描述】:
我想搭建一个小系统输入消费者信息,但是添加新信息的功能有一个bug。第一次可以正常添加,但第二次添加会无限添加结果。如图,有文件信息和程序。
先做一些处理
#include <stdio.h>
#include <stdlib.h>
//Create structure
struct stu_con {
long time;
int num; //student ID
char name[10];
double money;
struct stu_con *next;
};
struct stu_con *head;//Global variable head pointer
//Create a linked list and enter the file into the linked list
struct stu_con *create(struct stu_con *head) {
FILE *fp;
struct stu_con *p1, *p2, *p;
if ((fp = fopen("d:\\fee.txt", "r+")) == NULL) { //Open a D drive file
printf("Cannot open file!\n");
exit(0);
} else {
printf("Successfully opened the file!\n");
head = p1 = p2 = (struct stu_con *)malloc(sizeof(struct stu_con));
while ((fscanf(fp, "%d%d%s%lf", &p1->time, &p1->num, p1->name, &p1->money)) != EOF) { //getting information
p1 = (struct stu_con *)malloc(sizeof(struct stu_con));
p2->next = p1;
p2 = p1;
}
p1->next = NULL;
p1 = p2 = head;
while (p1->next != NULL) {
p2 = p1;
p1 = p1->next;
}
p2->next = NULL;
printf("The file is entered successfully!\n");
fclose(fp);
}
return head;
};
//Show the contents of the file
void show(struct stu_con *head) {
struct stu_con *p;
p = head;
while (p != NULL) {
printf("%d\t%d\t%s\t%.2lf\n", p->time, p->num, p->name, p->money);
p = p->next;
}
}
那么问题来了
//Add new information
struct stu_con *insert(struct stu_con *head, struct stu_con *bo) {
struct stu_con *p0, *p1, *p2;
p1 = head;
p0 = bo;
if (head == NULL) {
head = p0;
p0->next = NULL;
} else {
//According to the time to determine the location to join
while ((p0->time > p1->time) && (p1->next != NULL)) {
p2 = p1;
p1 = p1->next;
}
if (p0->time <= p1->time) {
if (head == p1)
head = p0;
else
p2->next = p0;
p0->next = p1;
} else {
p1->next = p0;
p0->next = NULL;
}
}
return head;
};
最后是main函数
//Main function
int main() {
struct stu_con bo;
head = create(head); //Create a linked list
show(head);
again_n: //Build a loop
printf("Please enter the student consumption information record you want to add:\n");
scanf("%d%d%s%lf", &bo.time, &bo.num, bo.name, &bo.money);
head = insert(head, &bo);
printf("The information is entered successfully. \n"
"Do you want to continue to enter it?(Y/N):");
getchar();
while (getchar() == 'Y')
goto again_n; //Loop
show(head); //Show results
return 0;
}
希望有人能帮助我,谢谢
【问题讨论】:
-
只是出于好奇,哪个教程在
do {...} while ()循环之前教goto? -
很抱歉我对循环结构不熟悉。我认为这样使用它是可以的。我需要更多地练习它。
-
都是同班授课的,只是我不能正确使用;-(
标签: c struct linked-list