Search code examples
cstringlistinputfgets

string input in linked list [C]


I am just learning about linked lists. I wrote a little programm for myself practising the mechanism about linked lists. This is my first attempt trying to do a small pokedex (without actually saving anything). So I am trying to setup the input correctly. Currently everything works fine, no errors and I can execute it.

The problem is the 2nd time of inputing the pokemon name it does not read in any data, instead it skips reading in and goes directly to the scanf function, why is that the case?

void addPokemon(void){

    pokemonPtr firstPtr;
    pokemonPtr thisPokemon;
    firstPtr = NULL;

    firstPtr =(pokemon *) malloc(sizeof(pokemon));
    firstPtr->name = malloc(sizeof(char) * POKEMON_LENGTH);

    printf ("Enter the name of the Pokemon.\n");
    fgets(firstPtr->name, POKEMON_LENGTH, stdin);

The problem is right here, this fgets is not really being executed, so basically it does not prompt the user to enter the string.

    printf ("Enter the number of the Pokemon.\n");
    scanf("%d",&firstPtr->number);

    firstPtr->next =(pokemon *) malloc(sizeof(pokemon));

    thisPokemon = firstPtr->next;

    int i = 0;

    while (i < 10){

        thisPokemon->name = malloc(sizeof(char) * POKEMON_LENGTH);

        printf ("Enter the name of the Pokemon.\n");
        fgets(thisPokemon->name, POKEMON_LENGTH, stdin);
        printf ("Enter the number of the Pokemon.\n");
        scanf("%d",&thisPokemon->number);

        thisPokemon->next =(pokemon *) malloc (sizeof(pokemon));
        thisPokemon = thisPokemon->next;

        i++;

    }

Solution

  • fgets stops reading when a newline character is read. In your example, stdin already has a '\n' in it so fgets takes it and is done. This is because scanf doesn't read the newline character you get when you enter the number, leaving it in stdin.

    Two solutions:

    Instead of fgets, use scanf("%s", name);. This works because %s will ignore white space and newlines before the string it takes.

    User getchar() to read the newline.