My text file reads as this:
George Washington, 2345678
John Adams, 3456789
Thomas Jefferson, 4567890
James Madison, 0987654
James Monroe, 9876543
John Quincy Adams, 8765432
Andrew Jackson, 7654321
Martin Van Buren, 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;
}
答案 0 :(得分:2)
您遇到的问题不是阅读,而是打印。
printf("Student %s has ID %d\n", d->name, &d->id);
使用&
(和系列)阅读时,您使用地址操作符scanf
,但是当您打印时会打印地址< / em>变量。
除了我在评论中提到的内容之外,你还有其他一些阅读文件的问题,那就是你的无链接:
temp->next = malloc(sizeof(struct node));
temp = temp->next;
temp->next = NULL;
这会在列表的末尾创建一个额外的节点,该节点将是未初始化的,这意味着当您使用数据时,它将导致undefined behavior。
实际上,对于我的评论中提到的问题,您将有两个额外节点。