Question

I've created a variable-sized array (VLA) and I want to fill it with using fgets functions in a for loop. However program passes the some functions and it strangely ignores the first fgets action.

My code is;

void editorMain(void)
{
    printf("Please enter the number of items:  ");
    scanf("%u", &itemQuantity);
    printf("\n\n");

    char itemNames[itemQuantity][ITEM_NAME_LEN+1];

    memset(&itemNames, 0, sizeof(itemNames));

    printf("Please enter the names of items:  \n");

    char line[ITEM_NAME_LEN+1];

    memset(&line, 0, sizeof(line));

    for (int i = 0; i < itemQuantity; ++i) {
        printf("#%d:  ", i + 1);

        memset(&line, 0, sizeof(line));

        fgets(line, ITEM_NAME_LEN+1, stdin);

        for (int a = ITEM_NAME_LEN+1; a >= 0; --a) {
            if (line[a] == '\n') {
                line[a] = 0;
            }

            else;
        }

        snprintf(itemNames[i], ITEM_NAME_LEN+1, "%s", line);
    }
...
}

And it outputs;

Please make a choice:  2

Please enter the number of items:  4


Please enter the names of items:  
#1:  #2:  Marlboro
#3:  Parliament
#4:  Winston

Please enter the prices of items:  
#1:  25
#2:  950
#3:  1000
#4:  800
  ................... AVAILABLE ITEMS oo

         #           Item Name          Price
         =           =========        =======

         1.                           0.25 TL
         2.           Marlboro        9.50 TL
         3.         Parliament       10.00 TL
         4.            Winston        8.00 TL

  Enter your item selection:  

What's your suggestion?

Was it helpful?

Solution

The scanf("%u" call reads up to the newline character, but leaves that character in the input stream. When you call your first fgets, it just reads that newline character and gives you an empty string.

There are many ways to clear the input stream, in this case you could just add a dummy call to fgets after your scanf.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top