gpt4 book ai didi

c - 将数据文件作为链表中的节点读取的函数

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:57 25 4
gpt4 key购买 nike

我的文本文件如下所示:
乔治华盛顿,2345678
约翰·亚当斯,3456789
托马斯·杰斐逊,4567890
詹姆斯·麦迪逊,0987654
詹姆斯梦露,9876543
约翰·昆西·亚当斯,8765432
安德鲁· jackson ,7654321
马丁·范布伦,6543210

但是,当我运行我当前的代码来显示时,我没有得到这些数字,最后得到的是随机数字,我该如何解决这个问题?您现在可以避免使用其他函数,因为我只是想确保文件读入不同的节点。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//Creates node for holding student's information
struct node
{
char name [50];
int id;
struct node *next;
}*head;

//Create Function Prototypes
void readDataFile ();
void display(struct node *d);
void deleteID(int num);
void deleteName(char dname);


//Main function
int main()
{
//Declare variables
int i, num, intid;
char *name;
char nameDelete [50];
char nameInsert [50];
struct node *n;

//initialize link list
head = NULL;

//Read in file
readDataFile();

//Create list of operations utilized in program
while (1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Delete by ID\n");
printf("4.Delete by Name\n");
printf("5.Exit\n");
printf("Enter your choice : ");

if(scanf("%d", &i) <= 0)
{
printf("Enter only an Integer\n");
exit(0);
}
else
{
switch(i)
{
case 1:
printf("Enter the name to insert: ");
gets(nameInsert);
printf("Enter the ID associated with the name: ");
scanf("%d", &intid);
break;
case 2:
if (head == NULL)
printf("List is Empty\n");
else
{
printf("Elements in the list are:\n");
}
display(n);
break;
case 3:
if(head == NULL)
printf("List is Empty\n");
else
{
printf("Enter the ID number to delete: ");
scanf("%d", &intid);
}
break;
case 4:
if(head == NULL)
printf("List is Empty\n");
else
{
printf("Enter name to delete: ");
gets(nameDelete);
}
case 5:
return 0;
default:
printf("Invalid option\n");
}
}
}
return 0;
}

最佳答案

您的问题不是阅读,而是打印

printf("Student %s has ID %d\n", d->name, &d->id);

当使用 scanf(和 family)read 时,您使用地址运算符 &,但是当您打印时,它将打印变量的地址


除了我在评论中提到的问题之外,您在读取文件时还有一些其他问题,那就是您的无链接:

temp->next = malloc(sizeof(struct node));
temp = temp->next;
temp->next = NULL;

这将在列表末尾创建一个额外节点,该节点将未初始化,这意味着当您使用数据时,它将导致 undefined behavior .

实际上,对于我评论中提到的问题,您将有两个 额外的节点。

关于c - 将数据文件作为链表中的节点读取的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28398415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com