In my code, I request a series of data from the user through the function gets()
, the problem is that at a certain point in the program, when requesting data with gets()
, it simply skips to the next request and leaves the variable blank, I have tried to clean the buffer of the following way and it doesn't work:
fflush(stdin);
This is the code:
#include <stdio.h>
#include <string.h>
struct alumnos{
char nombre[10];
char dni[20];
int edad;
};
int main(){
struct alumnos myalumno[3];
int i;
for(i=0;i<=2;i++){
printf("Ingrese el nombre del alumno %i: ",i+1);
fflush(stdin);
gets(myalumno[i].nombre);
printf("Ingrese el DNI del alumno %i: ",i+1);
fflush(stdin);
gets(myalumno[i].dni);
printf("Ingrese la edad del alumno %i: ",i+1);
fflush(stdin);
scanf("%i",&myalumno[i].edad);
}
}
Taken from here which
fflush
is only used in output buffers.Try to use
fpurge
:Where...
If a
fflush
is givenNULL
as a parameter, it will clear all active output buffers, butfpurge
it only takes the input buffer and clears it.You must be careful with the use of
fpurge
, it is not a "portable" solution to other platforms, so you should be careful when using it.Reference: fpurge (In English)
With that it should work.
Since the behavior of
fflush
is not defined by the standard for input streams, it is only certain to work for output streams (sending the remaining contents of the buffer to the output). Therefore youfflush
should not use it.It is also not recommended to use
fpurge
since it is not defined in standard C and it is also not portable to all platforms (as explained in other comments). In fact, it is not available on Linux, although there is a functionvoid __fpurge(FILE *stream)
that does the same thing and it is within the GNU standard library (glibc).The possible solution is for you to manually write code that clears the input buffer until it finds a newline. The two options you have are:
and the one that seems better to me:
In the last option, first is told to
scanf
ignore (using *) any number of non-blank characters (other than tab'\t'
, space ,' '
or newline'\n'
) with the specifier%*[^\n]
until it finds a blank character (the newline ), in which case it ignores it with the%*c
.The
%*c
can't be substituted for\n
because in that case you'd be commanding at that point to ignore any number of blank characters until it finds one that isn't, causing the scanf function to hang around waiting for you to enter any non-blank characters, the which will not be read and will remain pending in the input buffer for the next call toscanf
.Keep in mind that these solutions are valid in the event that the buffer has content other than blank characters (
' ', '\t' o '\n'
). If the buffer is empty, it will wait for data to be entered by keyboard other than blank characters (data that it will ignore).