Question

#include<stdio.h>
#include<string.h>
int main()
{
    char name[10][30];
    int i,n;
    printf("How many names?\n");
    scanf("%d",&n);
    printf("Enter names\n");
    for(i=0;i<n;++i)
        gets(name[i]);
    printf("\n The names are\n");
    for(i=0;i<n;++i)
        printf("%s\n",name[i]);
}

I am trying to sort the full name of persons in order. So I read total number of names and store the names in an array of string. But the problem is when this program is executed:

 How many names
 4
 Enter names
 john G
 susan sing
 puskar
 The names are

 john G
 susan sing
 puskar

I am not getting why an empty string is been read.

Was it helpful?

Solution

scanf("%d", &n);

reads an integer from standard input. Anything following that integer, particularly the new line that you entered when you typed Enter after the 4, is left waiting to be read by the next input routine, in this case the first gets().

You got a blank line because that's what you gave it after the 4.

That's the immediate cause of the problem you asked about, but you've got bigger problems.

Never use the gets function. It does not guard against input that's longer than the array you're reading into, and it cannot be used safely. That's why it's been removed from the language as of the 2011 ISO C standard.

You can use fgets to read a line of input, and then sscanf to extract the integer from the line in memory. fgets, unlike gets, leaves the '\n' in your array, so you'll have to deal with that (though you can ignore it when reading n). Read the documentation for both functions, and pay attention to the values they return. (They have some problems of their own, but you don't need to worry about that for now.)

OTHER TIPS

Mixing scanf() with fgets()/gets() is problematic.

Suggest using fgets() instead of gets() as gets() is dead.

// scanf("%d",&n);
char buf[50];
fgets(buf, sizeof buf, stdin);
sscanf(buf, "%d", &n);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top