While the definition does not specify fflush
for an input stream such as stdin , some compilers support this, which causes your problem in such cases to be resolved by changing setbuf(stdin,NULL);
by:
fflush(stdin);
Another alternative, which follows the definition correctly, is to read what is missing until the end of the line, if the read exceeds the limit indicated in fgets
. To see if you have read to the end of the line, you can find \n
on the line using the strchr
function. , which will return NULL
if it does not exist, or a valid pointer if it exists.
Implementation:
for(i=0; i<MAX; i++) {
printf("\nForneça o nome do %dº produto:",i+1);
fgets(nomes[i],QCH,stdin);
if(!strchr(nomes[i], '\n')){ //se o nome não tem \n então ultrapassou o limite
scanf("%*[^\n]"); //lê até ao final da linha
scanf("%*c"); //lê a quebra de linha
}
}
See this example working on Ideone
Note that the readings in scanf
were made with *
because what is read is to be discarded, and thus avoids having to create a variable just to read what's left.
The setbuf
function indicates whether the read and write readings are buffered, which means that they can not be made the moment you call them. This is however not related to discarding what was left over in the input stream.