Kindle Kindle -4 years ago 147
C Question

String input in array using gets function

int main()
char name[10][30];
int i,n;
printf("How many names?\n");
printf("Enter names\n");
printf("\n The names are\n");

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
Enter names
john G
susan sing
The names are

john G
susan sing

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

Answer Source
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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download