0
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main()
{
    int n,i;
    char a[10][100];
    printf("\n Enter the no. of strings:");
    scanf("%d",&n);

    printf("\n enter the %d numbers:",n);

    for(i=0;i<n;i++)
    {
        printf("\n %d",i);

        gets(a[i]);
    }
    for(i=0;i<=n;i++)
        {
            puts(a[i]);
        }
    return 0;
}

If n = 3 then it takes only two strings at index 1 and 2 it skips 0, why doesn't it take input at 0 ?

Here a is my array of strings.

Suraj Jain
  • 4,463
  • 28
  • 39
ash
  • 39
  • 8
  • 1
    `gets` is a function that is impossible to use correctly. As such, it's been removed from the latest C standard. Using it is a bug. Please consider using `fgets` instead. – user694733 Feb 24 '17 at 06:39
  • 2
    Because the `scanf` before it leaves a `\n` in the input buffer and `gets` reads it in the first iteration. BTW, [**Never use `gets`**. It is dangerous!](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Spikatrix Feb 24 '17 at 06:42

1 Answers1

0

The reason for wrong behavior is that scanf does not read the ENTER which is necessary to confirm the input of n. If you add dummy call of gets it does:

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main()
{
    int n,i;
    char a[10][100];
    printf("\n Enter the no. of strings:");
    scanf("%d",&n); gets(a[0]);

    printf("\n enter the %d numbers:",n);

    for(i=0;i<n;++i)
    {
        printf("\n %d",i);

        gets(a[i]);
    }
    for(i=0;i<n;++i)
        {
            puts(a[i]);
        }
    return 0;
}

Please diff my version with the original one. I did fix another issue in the output loop.

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56