4

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.

Vartika
  • 77
  • 1
  • 6
  • 1
    To begin with, never ***ever*** use `gets`. It's [a dangerous function](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) and has therefore even been removed from the C standard. – Some programmer dude Oct 27 '18 at 10:48
  • have tried `fgets` also. problem is that it is not taking input for str[0] – Vartika Oct 27 '18 at 10:59

2 Answers2

4

You need to consume the remaining buffer leaved by scanf:

scanf("%d", &n);
char str[n][60];
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF);
printf("start entering strings:\n ");

You can avoid the ugly flush loop using fgets and strtol instead of scanf:

char buf[32];
int i, n = 0;

printf("how many string you want to enter: ");
if (fgets(buf, sizeof buf, stdin)) {
    n = (int)strtol(buf, NULL, 10);
}

char str[n][60];
printf("start entering strings:\n ");
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621