我是新来的,这是我的第一个问题:
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Person{
char *vorname;
char *nachname;
};
typedef struct Person Person;
struct Node{
Person *data;
struct Node *next;
};
typedef struct Node Node;
void addToList(Person *p);
void readFile();
Node *start = NULL;
void readFile(){
FILE *f;
Person *p;
char input[501];
char *line;
f = fopen("persdat.txt", "r");
while(fgets(input, 500, f) != NULL){
line = strtok(input, ";");
strcpy(p->vorname, line);
line = strtok(NULL, ";");
strcpy(p->nachname, line);
printf("%s wurde eingelesen.\n", p->vorname);
addToList(p);
line[0] = '\0';
}
}
void addToList(Person *p){
Node *newNode = malloc(sizeof(Node));
newNode->data = p;
newNode->next = NULL;
if (start == NULL){
start = newNode;
printf("%s wurde in die Liste eingefügt. (1. Stelle)\n", newNode->data->vorname);
}else{
Node *current = start;
int stelle = 2;
while(current->next != NULL){
printf("Liste wird durchlaufen... aktuelle Person: %s\n", current->data->vorname);
current = current->next;
stelle++;
}
current->next = newNode;
printf("%s wurde in die Liste eingefügt (%d. Stelle).\n", newNode->data->vorname, stelle);
}
}
void output(){
Node *current = start;
printf("%s\n", current->data->vorname);
do{
current = current->next;
printf("%s\n", current->data->vorname);
}while (current->next != NULL);
}
int main(int argc, char *argv[]) {
printf("\n");
readFile();
output();
return EXIT_SUCCESS;
}
该结构Person
具有成员char *vorname
和char *nachname
。该结构Node
具有成员Person *data
和结构Node *next
(我 typedef'ed)。start 是声明的列表。
这是我正在使用的文本文件:
Daniel;Smith
Florian;Mayne
Michael;Fabour
Manuel;Spoley
Andrea;Bree
Prapot;BumBum
Tobias;Sinkleeser
Nikolaus;Muffed
终端输出:
函数 output() 打印 8 次Nikolaus
,而我希望它输出我在列表中插入的 8 个名称,这是为什么呢?