data structures - Linked list in C with fgets() -
i'm having issues code skipping first question in second data structure. i'm pretty sure it's because gets(), not sure. think tried fgets(), still giving me issues. why?
#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 name of actress/actor: "); gets(node->name); printf("please enter actress/actor place of birth: "); gets(node->placeofbirth); printf("please enter actress/actor hair color: "); gets(node->haircolor); printf("please enter actress/actor age: "); scanf("%d", &node->age); printf("please enter actress/actor networth: "); scanf("%f", &node->networth); } void displaystruct(actress *head) { actress *crawler; crawler = head; while(crawler != null) { printf("the name of actress/actor is: %s\n", crawler->name); printf("the place of birth actress/actor is: %s\n", crawler->placeofbirth); printf("the hair color of actress/actor is: %s\n", crawler->haircolor); printf("the actress/actor age is: %d\n", crawler->age); printf("the networth actress/actor %f\n", crawler->networth); crawler = crawler->next; } } int main() { int i; actress *head = (actress *) malloc(sizeof(actress)), *crawler; crawler = head; (i = 0; < 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; }
mixing fgets
, scanf
turns out badly. reason scanf
leave newline character in input stream, , following fgets
therefore read empty line. , using gets
just plain wrong.
the solution read input fgets
, , parse input sscanf
needed. cases sscanf
not needed, i.e. input string, can use strcspn
remove newline buffer.
int populatestruct(actress *node) { char buffer[100]; printf("please enter name of actress/actor: "); if ( fgets( buffer, sizeof buffer, stdin ) == null ) return 0; buffer[strcspn(buffer,"\n")] = '\0'; if ( (node->name = malloc(strlen(buffer) + 1)) == null ) return 0; strcpy( node->name, buffer ); // ditto place of birth , hair color printf("please enter actress/actor age: "); if ( fgets( buffer, sizeof buffer, stdin ) == null ) return 0; if ( sscanf( buffer, "%d", &node->age ) != 1 ) return 0; printf("please enter actress/actor networth: "); if ( fgets( buffer, sizeof buffer, stdin ) == null ) return 0; if ( sscanf( buffer, "%lf", &node->networth ) != 1 ) return 0; return 1; }
oh, , changed networth
float
double
. float
has 6 or 7 digits of precision, , that's not enough net worth of actress/actor.
Comments
Post a Comment