One of the fgets() commands is not executed

Asked

Viewed 33 times

0

The code runs normally until it arrives at the part where it is asked to insert the units of the component. I did not insert anything and it already closes the program.

  #include <stdio.h>
    #include <stdlib.h>

//estruturas de dado
struct componente{
    char tipo[20],referencia[4],unidade[10];
    unsigned char num_ref;
    int valor;
}comp/*,comp1,comp2 */;

//struct componente comp;
int main(int argc,char *argv[])
{
        printf("\n\n**********CADASTRAR COMPONENTE***********\n");  
    printf("Tipo do componente _ ");
    fflush(stdin);
    fgets(comp.tipo,20,stdin);

    printf("Referência do componente _");
    fgets(comp.referencia,4,stdin);

    printf("Número de referência do componente _");
    scanf("%c",&comp.num_ref);
    //getchar();

    printf("Valor do componente_ ");
    scanf("%d",&comp.valor);

    printf("Unidades _ ");
    fflush(stdin);
    fgets(comp.unidade,10,stdin);

    printf("\n\n**********COMPONENTE CRIADO***********\n"); 
    printf("*Tipo do componente:%s",comp.tipo);
    printf("*Referência do componente:%s",comp.referencia);
    printf("*Número de referência do componente:%c",comp.num_ref);
    printf("*Valor do componente:%d",comp.valor);
    printf("*Unidade: %s",comp.unidade);

    system("PAUSE");
    return 0;
}
  • the reference number has letters or only numbers? if it has only numbers it is easier to use scanf("%d")

  • One ' n' is left in the input buffer after reading comp.num_ref. Clear the buffer before reading.

1 answer

0

Solved. I added a getchar() after reading comp.valor and also put a fflush(stdin) before reading comp.referencia.

  • Just be aware that fflush(stdin) has undefined behavior depending on the operating system used.

  • I didn’t know that. I’ll look into

  • See questions 12.26a and 12.26b by http://www.faqs.org/faqs/C-faq/faq/.

Browser other questions tagged

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