0

I am trying to write a C program that takes n as an integer input and then inputs n strings. The problem that when I run the program, it takes one input less than n. If I enter 1 as the first input the program just terminates. Here is the code :

int n;
scanf("%d", &n);
char str[101];

while (n--) {
    fgets(str, 101, stdin);
    // other stuff...
}

What am I doing wrong here?

fenceop
  • 1,439
  • 3
  • 18
  • 29
helios_xt
  • 87
  • 8

3 Answers3

3

Your program will work if you use scanf() for the number and the string input.

#include <stdio.h>

int main()
{
    int n;
    char str[101];
    scanf("%d", &n);
    while (n--)
    {
        scanf("%s", str);
    }
    return 0;
}

But it's arguably better to use fgets() for all the inputs.

#include <stdio.h>

int main()
{
    int n;
    char str[101];
    fgets(str, 100, stdin);
    sscanf(str, "%d", &n);
    while (n--)
    {
        fgets(str, 100, stdin);
    }
    return 0;
}

I scarcely need to remind you since you used fgets() in the first place, you'll be aware that it retains the newline at the end of the input string.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • 2
    Note: Better to use `fgets(str, sizeof str, stdin);` 1) is should be 101 not 100 and 2) avoid magic numbers. +1 for "better to use fgets() for all the inputs." – chux - Reinstate Monica Jul 11 '15 at 04:43
1

Remember that hitting the enter key sends a character to the stream too. Your program fails to account for this. Use the format scanf(%d%*c) to discard the second character.

int main(void) {

    int n;

    scanf("%d%*c", &n);

    char str[101];

    while (n--)
    {
        fgets(str, 101, stdin);

        // other stuff.....
    }

}
PC Luddite
  • 5,883
  • 6
  • 23
  • 39
1
int n;
scanf("%d", &n);
char str[101];

while (n--) 
{
fgets(str, 101, stdin);
// other stuff...
}

In this as you enter n and press ENTER from keyboard '\n is stored in stdin therefore as fgets encounters newline character if returns .

Therefore use this after scanf-

 char c ;
while((c=getchar())!=NULL && c!='\n');
ameyCU
  • 16,489
  • 2
  • 26
  • 41