It's because of your use of scanf
earlier in the code. When you enter the number as input, you press the Enter key to mark the end of the input and that adds a newline in the input buffer. What scanf
does is read the number, but leave the newline (enter key) in the input buffer. Then when you call fgets
it sees this lone newline and reads it.
A very simple solution to this is to tell scanf
to skip trailing whitespace by adding a single space after the format code:
scanf("%d ", &limit);
/* ^ */
/* | */
/* Note space here */
If the above solution doesn't work, then you can read characters until you get a newline:
int c;
while ((c = fgetc(stdin)) != EOF && c != '\n')
;
Also, in Mac OSX there is the fpurge
function which can be used to clear unread data from an input stream:
fpurge(stdin);
Note: Thefpurge
function is not portable.
On Linux and Windows you can use fflush
to perform the same thing fpurge
does, but note that it's extensions in the libraries for Linux and Windows that allows it. Calling fflush
on an input stream is, according to the C specification, undefined behavior. See e.g. the Linux manual page or the Windows reference page.