Although the definition does not specify fflush
for a stream incoming as the stdin, some compilers support this, which makes your problem in such cases can be solved by swapping setbuf(stdin,NULL);
for:
fflush(stdin);
Another alternative, which follows the definition correctly, is to read what is missing until the end of the line, if what was read exceeds the limit indicated in fgets
. To find out if you read to the end of the line you can find the \n
on the line using the function strchr
, who will return NULL
if no, or a valid pointer if any.
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 on scanf
were made with *
because what is read is to be discarded, and so avoids having to create a variable just to read what is left.
The function setbuf
indicates whether the readings and or writings are bufferized, implying that they may not be done at the time you call them. This however is not related to discarding what got the most in the input stream.