buffer is not cleared during second run of the cycle

1

During the second execution of the for loop, setbuf did not work, and if the 2nd product had more than 14 characters, it assigned the remaining 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;
}
    
asked by anonymous 30.05.2018 / 02:11

1 answer

0

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.

    
30.05.2018 / 02:34