Problem with scanf and fgets

It is for homework to sort some given lines. I ask the user for the number of rows that they would like to sort with scanf, allocating an array based on that number, and then getting the rows themselves with fgets.

Everything works fine if the number of lines is hard-coded, but adding scanfallows the user to solve problems with the screws. Here is the code:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

#define LENGTH  20 // Maximum string length.

int main(void)
{
    int index, numStrings = 0;
    char **stringArray;
    printf("Input the number of strings that you'd like to sort: ");
    assert(scanf("%d", &numStrings) == 1);
    stringArray = (char **)malloc(numStrings * sizeof(char *));

    for (index = 0; index < numStrings; index++)
    {
        stringArray[index] = (char *)malloc(LENGTH * sizeof(char));
        assert(stringArray[index] != NULL);
        printf("Input string: ");
        assert(fgets(stringArray[index], LENGTH, stdin) != NULL);
    }

    // Sort strings, free allocated memory.

    return 0;
}

And this is what the console looks like:

Input the number of strings that you'd like to sort: 3
Input string: Input string: foo
Input string: bar

It skips the first iteration of the loop, which leads to an empty line at the beginning of the array. My question is: why does he do it and how to fix it?


"%d\n", scanf:

Input the number of strings that you'd like to sort: 3
foo
Input string: Input string: bar
Input string: baz

, , .

+3
2

( , : P) scanf. fgets (.. ), , , sscanf strtoul. , , - , scanf .

, int , -4. size_t , , . .

+3

scanf, \n, \n scanf:

scanf("%d\n", &numStrings)

, scanf [ ]

+6

Source: https://habr.com/ru/post/1790612/


All Articles