The system is not reading the requested line

Asked

Viewed 32 times

0

I made the code below to read simple date information, but when it reads the day, it strangely asks for two entries, and ends up going one to the variable diatemp and the other to the mestemp, without calling the printf("Type the month"), this ends up making it impossible to continue the program, someone has some suggestion of what I could do to solve this problem?

void PegarDadosIniciais(){

    //Data dataAtual;

    int diatemp, mestemp, anotemp;

      printf(" @----------------------------------------------------------------------------@\n");
    printf(" | ");printf("\t\t\t     SISTEMA DE LOCACAO DE VEICULOS");printf("\t\t      |\n");
    printf(" @----------------------------------------------------------------------------@\n");
    printf("\n");
    printf("Bem vindo ao sistema de locacoes de veiculos!! \n");
    printf("%s\n","Precisaremos de alguns dados para iniciar o sistema.." );
    printf("%s\n\n","PRESSIONE ENTER PARA CONTINUAR.." );
    getch();
    system("cls");
    printf(" @----------------------------------------------------------------------------@\n");
    printf(" | ");printf("\t\t\t     CONFIGURACOES INICIAIS");printf("\t\t      |\n");
    printf(" @----------------------------------------------------------------------------@\n");
    printf("\n");
    printf("%s\n",">>INSIRA A DATA ATUAL<<" );
    printf("%s", "Insira o dia: " );
    scanf("%d\n", &diatemp);
        printf("%s\n","Insira o mes: " );
    scanf("%d\n", &mestemp);
        printf("%s\n","Insira o ano: " );
    scanf("%d\n", &anotemp);
    printf("%d/%d/%d",diatemp, mestemp, anotemp);
    getch();


}
  • Probably taking the keyboard buffer, puts another getch() or use system("pause")

1 answer

1

The problem is in \n the most in readings with scanf:

printf("%s", "Insira o dia: " );
scanf("%d\n", &diatemp);
//        ^-- aqui
printf("%s\n","Insira o mes: " );
scanf("%d\n", &mestemp);
//        ^-- aqui
printf("%s\n","Insira o ano: " );
scanf("%d\n", &anotemp);
//        ^-- aqui

This makes the input have to take one more Enter only the first value is consumed.

Correct would be:

printf("%s", "Insira o dia: " );
scanf("%d", &diatemp);
printf("%s","Insira o mes: " );
scanf("%d", &mestemp);
printf("%s","Insira o ano: " );
scanf("%d", &anotemp);

Some remarks:

  • printf("%s\n","Insira o mes: " ); Here complicated a little, much simpler was to do printf("Insira o mes: \n" );
  • Avoid using getch because it is not something portable to other operating systems.

Browser other questions tagged

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