0

I’m trying to write a code which stores some strings in an array with fgets, but it doesn’t let me input the string of index 0 of the array. Can someone help me?

#include <stdio.h>
#include <stdlib.h>
int main(){
int lenght;
int i;
printf("Enter the lenght: ");
scanf("%d", &lenght);
char array[lenght][20];
for(i=0; i<lenght; i++)
{
printf("Enter the %d string: ", i);
fgets(array[i], 30, stdin);
}
for(i=0; i<lenght; i++)
{
printf("%s ", array[i]);
}
return 0;
}
Arthur
  • 1
  • 1
  • The call to `scanf()` leaves the newline in the input buffer, so the first call to `fgets()` reads that newline, appearing to be an empty line. Add `int c; while ((c = getchar()) != EOF && c != '\n') ;` (three lines of code) after the `scanf()` to gobble up the newline. Or create `static void gobble(void) { int c; while ((c = getchar()) != EOF && c != '\n') ; }` and simply call `gobble();` after the `scanf()`. – Jonathan Leffler Apr 07 '22 at 13:29
  • or just use fgets to read the line with the length, then sscanf to extract the number from the string. – stark Apr 07 '22 at 14:01
  • Or pass the length as a command line argument rather than reading it from stdin, (or don't pass the length at all and just read until the input stream is terminated) – William Pursell Apr 07 '22 at 14:16
  • Why are you passing `30` as the 2nd parameter to `fgets`, when each buffer is only size 20? Use `fgets(array[i], sizeof array[i], stdin);` – William Pursell Apr 07 '22 at 14:23

0 Answers0