Search code examples
cmultidimensional-arrayfgetsc-stringsgets

fgets() / gets() problem while taking input for N strings. Not taking input at initial position


I need to get input for n (user-inputted) strings. For that I start with defining a two-dimensional array char str[ ][ ].
I used for loop getting input from user and have tried gets(), fgets() both. In code example although I used gets().
But it is always taking input for n-1 strings, i.e, 1 less than user want to enter.
Upon further checking I found that program is not taking input for 0th string, i.e., initial string.

My code:

#include <stdio.h>
int main(void){
int i, n;

printf("how many string you want to enter: ");
scanf("%d", &n);

char str[n][60];

printf("start entering strings:\n ");

for(i=0;i<n;i++){     
    gets(str[i]);     //have used here fgets() also
}

puts(str[0]);         //no output for Oth string
return 0;
}

Output:

how many string you want to enter:

User input - 3

how many string you want to enter: 3
start entering strings:

Final Output:

how many string you want to enter: 3
start entering strings:
 abc
bcd

Here program terminates after taking input for only 2 strings and not giving any ouput for puts(str[0]);

Although taking input with scanf() as scanf("%s", str[i]); worked perfectly fine.
I want to know why using gets(), fgets() didn't worked.


Solution

  • The problem isn't with fgets (or gets for that matter). The problem is your previous call to scanf.

    When you end the input of the number with the Enter key, that Enter key will be added to the input buffer as a newline. So after scanf have read the number, the next character left in the input buffer will be that newline. And that's the first character that fgets will read, as an empty line. So it does read all the lines, but the first will be considered empty.

    And that's why you don't seem to get any output, because there's no printable characters to print. All you get is an empty line.