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



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 Operationsn");
    printf("===============n");
    printf("1.Insertn");
    printf("2.Displayn");
    printf("3.Delete by IDn");
    printf("4.Delete by Namen");
    printf("5.Exitn");
    printf("Enter your choice : ");
    if(scanf("%d", &i) <= 0)
    {
        printf("Enter only an Integern");
        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 Emptyn");
                else
                {
                    printf("Elements in the list are:n");
                }
                display(n);
                break;
            case 3:
                if(head == NULL)
                    printf("List is Emptyn");
                else
                {
                    printf("Enter the ID number to delete: ");
                    scanf("%d", &intid);
                }
                break;
            case 4:
                if(head == NULL)
                    printf("List is Emptyn");
                else
                {
                    printf("Enter name to delete: ");
                    gets(nameDelete);
                }
            case 5:
                return 0;
            default:
                printf("Invalid optionn");
        }
    }
}
return 0;
}

问题不在于阅读,而在于打印

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

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


除了我在评论中提到的,你在阅读文件时也有其他问题,那就是你的无链接:

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

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

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

相关内容

  • 没有找到相关文章

最新更新