buffer is not cleaned during the second execution of cilclo

Asked

Viewed 39 times

1

During the second execution of the loop for the setbuf no Urti effect and if the 2nd 'product' has more than 14 characters assigned the other characters to the next positions.

#include <stdio.h>

 const int MAX=5;
 const int QCH=15;

int main(){

char nomes[MAX][QCH];
int i;

for(i=0;i<MAX;i++){
    printf("\nForneça o nome do %dº produto:",i+1);
    fgets(nomes[i],QCH,stdin);
    setbuf(stdin,NULL);
}


for (i=0;i<MAX;i++){
    printf("\n%s",nomes[i]);
}

return 0;
}

1 answer

0


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.