I have often seen cases where in a series of printf statements that ask for an input, certain
statements do not accept an input, i.e.
printf_statement1:
printf_statement2: /*Enter input here*/
i.e. before the user enters an input for statement1, statement2 is printed, that allows the user to enter an input, and then repeats the same with statement3 & statement4.
What prompts such a case?
I encounterd this, but not any more, in:
printf("\n\n\t\tName: ");
scanf("%s", name); //initially used gets
printf("\n\n\t\tType: ");
scanf("%c", &type);
printf("\n\n\t\tAddress: "); //initially used gets
scanf("%s", address);
printf("\n\n\t\tDate - of - Birth: ");
scanf("%s", dob); //initially used gets
Output:
Name:
Type: I enter something!
Address:
Date - of - Birth: I enter something!
Sometimes in cases like these, it is helpful to call
fflush()onstdinbefore reading from it:Depending on the circumstances, there may be a newline in the input buffer that causes your first
scanfto get skipped (given no input).Also note that you should specify the size of the buffer in
scanfas to avoid buffer overflows.A format specifier for scanf looks like this:
Thus, the
%40sspecifies that only 40 characters may be read in to the string. Note that the buffer is 41 characters, leaving room for the NULL terminator.Edit: Some sources (like this and this) say that you should avoid calling
fflush(stdin)and it is incorrect. However, the Linux man page states:Additionally: MSDN says nothing about calling
fflush(stdin)other than the following:One would think that if calling
fflush(stdin)was such a problem, one of the two largest sources of documentation onfflushwould have mentioned this.