Ich habe Probleme mit meinem Code überspringe die erste Frage in der zweiten Datenstruktur. Ich bin mir ziemlich sicher, es ist, weil das(), aber nicht sicher ist. Ich glaube, ich habe versucht, fgets(), aber es gab mir immer noch Probleme. Warum?Verknüpfte Liste in C mit fgets()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NumberOfActresses 5
typedef struct Actress
{
char *name, *placeofbirth, *haircolor;
int age;
float networth;
struct Actress *next;
} Actress;
void PopulateStruct(Actress *node)
{
node->name = (char *) malloc(sizeof(char) * 50);
node->placeofbirth = (char *) malloc(sizeof(char) * 50);
node->haircolor = (char *) malloc(sizeof(char) * 50);
printf("Please enter the name of the actress/actor: ");
gets(node->name);
printf("Please enter the actress/actor place of birth: ");
gets(node->placeofbirth);
printf("Please enter the actress/actor hair color: ");
gets(node->haircolor);
printf("Please enter the actress/actor age: ");
scanf("%d", &node->age);
printf("Please enter the actress/actor networth: ");
scanf("%f", &node->networth);
}
void DisplayStruct(Actress *head)
{
Actress *crawler;
crawler = head;
while(crawler != NULL)
{
printf("The name of the actress/actor is: %s\n", crawler->name);
printf("The place of birth for the actress/actor is: %s\n", crawler->placeofbirth);
printf("The hair color of the actress/actor is: %s\n", crawler->haircolor);
printf("The actress/actor age is: %d\n", crawler->age);
printf("The networth for the actress/actor is %f\n", crawler->networth);
crawler = crawler->next;
}
}
int main()
{
int i;
Actress *head = (Actress *) malloc(sizeof(Actress)), *crawler;
crawler = head;
for (i = 0; i < NumberOfActresses; i++)
{
PopulateStruct(crawler);
if (i == 2)
crawler->next = NULL;
else
crawler->next = malloc(sizeof(Actress));
crawler = crawler->next;
}
crawler = NULL;
DisplayStruct(head);
return 0;
}
'scanf ("% f ", & node-> networth);' -> 'scanf ("% f% * c ", & node-> networth);' '% * c' verbrauchen verbleibenden Zeilenumbruch. Auch 'if (i == 2)' -> 'if (i == 4)'? – BLUEPIXY
Mischen von 'fgets' und' scanf' ist immer schlecht. Und mit 'gets' ist es einfach falsch. – user3386109
@BLUEPIXY Entschuldigung, die if-Anweisung soll lesen, wenn (I == NumberOfAktives - 1). Mit dem% * c wird dieses Problem behoben oder sollte ich etwas anderes verwenden? – humbleCoder