I believe scanf
is using buffered input. It allows you to enter characters until you press enter. At that point, it takes the 20 that you specify, and the remaining buffer is then used as the input for the next scanf
call. fgets
's results are more predictable, with the next string being populated with the remnants of the previous buffer.
I cannot, however, explain why last name is blank, yet email is not in the first example.
Take a look here for an example of how to flush the type-ahead input. You can write a function like so:
void flushInput(void)
{
int c;
while((c = getchar()) != '\n' && c != EOF)
/* discard */ ;
}
...and then call flushInput();
after each scanf()
.
As an additional note, I believe you should be specifying one character less in your scanf
calls. It appears that....
char nameF[20];
scanf("%20s", nameF);
...is putting 20 characters into nameF
and the '\0'
terminator is going beyond the bounds of the array. fgets
appears to properly place the terminator within the specified size.