So I've implemented this simple and pretty useless doubly linked list just for the sake of practice. It is a list of athletes and the sport they play. Each node is defined as follows:
typedef struct node {
char* name;
char* sport;
struct node* prev;
struct node* next;
}node;
I've created the first node of the list in main (node* head is globally defined):
head = malloc(sizeof(node));
if (head == NULL) {
printf("malloc failed");
return 1;
}
head->name = "Stephen Curry";
head->sport = "Basketball";
head->next = NULL;
head->prev = NULL;
This do while loop is intended to allow the user to add as many nodes as he/she wants to the list at the terminal:
char names[50]; // declaring the arrays wherein the names and sports will be stored temporarily
char sports[30];
char YorN; // this will store the result from the prompt
do {
printf("name: ");
fgets(names, 50, stdin);
strtok(names, "\n"); // removing the "\n" that fgets adds so that name and sport will be printed on the same line
printf("sport: ");
fgets(sports, 30, stdin);
addNode(names, sports); // adds node to the head of the list
printReverse(); // prints the list in reverse, giving the illusion that the user is adding to the tail
printf("add a new name to the list? (Y or N): ");
YorN = fgetc(stdin);
YorN = toupper(YorN);
} while (YorN == 'Y');
It works fine for the first entry. output:
name: Reggie Miller
sport: Basketball
Stephen Curry,Basketball
Reggie Miller,Basketball
add a new name to the list? (Y or N):
After that if the user selects "Y" to add a new node, the terminal prints this:
name: sport:
which only allows the user to enter the sport. Then outputs this:
name: sport: k
Stephen Curry,Basketball
,k
,k
add a new name to the list? (Y or N):
where "k" is the sport entered. I don't think it's an issue with my addNode() or printReverse() functions so I've omitted posting those for the sake of brevity. However if someone thinks that it may be an issue with those functions or just would like to see them I'd be happy to post them. It just seems to me it is an issue with some aspect of the loop, maybe my implementation of fgets? When I tried scanf it failed on even the first attempt. Any help is much appreciated, thanks!