string input in linked list [C] -
i learning linked lists. wrote little programm myself practising mechanism linked lists. first attempt trying small pokedex (without saving anything). trying setup input correctly. works fine, no errors , can execute it.
the problem 2nd time of inputing pokemon name not read in data, instead skips reading in , goes directly scanf function, why case?
void addpokemon(void){ pokemonptr firstptr; pokemonptr thispokemon; firstptr = null; firstptr =(pokemon *) malloc(sizeof(pokemon)); firstptr->name = malloc(sizeof(char) * pokemon_length); printf ("enter name of pokemon.\n"); fgets(firstptr->name, pokemon_length, stdin);
the problem right here, fgets not being executed, not prompt user enter string.
printf ("enter number of pokemon.\n"); scanf("%d",&firstptr->number); firstptr->next =(pokemon *) malloc(sizeof(pokemon)); thispokemon = firstptr->next; int = 0; while (i < 10){ thispokemon->name = malloc(sizeof(char) * pokemon_length); printf ("enter name of pokemon.\n"); fgets(thispokemon->name, pokemon_length, stdin); printf ("enter number of pokemon.\n"); scanf("%d",&thispokemon->number); thispokemon->next =(pokemon *) malloc (sizeof(pokemon)); thispokemon = thispokemon->next; i++; }
fgets stops reading when newline character read. in example, stdin has '\n' in fgets takes , done. because scanf doesn't read newline character when enter number, leaving in stdin.
two solutions:
instead of fgets, use scanf("%s", name);
. works because %s
ignore white space , newlines before string takes.
user getchar() read newline.
Comments
Post a Comment