Reading on the same line

Asked

Viewed 1,023 times

1

I have a struct to define the type DATA.

typedef struct data {
    int ano, mes, dia;
}DATA;

DATA nasc;

Now, I will read this information from the user input.

printf("Digite sua data de nascimento");
scanf("%d", &nasc.dia);
printf("/");
scanf("%d", &nasc.mes);
printf("/");
scanf("%d", &nasc.ano);

I would like to do this in a better way. Reading the three entries on the same line and printing the character / after each entry.

How can I do that?? How to continue on the same line after an input??

2 answers

1

Just do it this way:

scanf("%d/%d/%d", &nasc.dia, &nasc.mes, &nasc.ano);

Remembering that the user will need to write the date using the bars.

Functional example in ideone

  • This helps a lot! But I would still like to know if you have how to insert the bars between the inputs... for interface sake.

0

In Windows environment, you could try something like:


#include &ltstdio.h>
#include &ltconio.h>
#include &ltstring.h>

typedef struct data {
   int ano, mes, dia;
}DATA;

int aux(char str[]){

   int my_number;
   str[0] = getche();
   str[1] = getche();
   my_number = atoi(str);
   return my_number;
}


int main(){

   DATA nasc;

   char str[3];
   str[2] = '\0';

   printf("Digite sua data de nascimento.\n");
   printf("  /  /\r");
   nasc.dia = aux(str);
   printf("\r%.2d/  /\b\b\b", nasc.dia);
   nasc.mes = aux(str);
   printf("\r%.2d/%.2d/", nasc.dia, nasc.mes);
   nasc.ano = aux(str);

   printf("\n\n%.2d/%.2d/%.2d", nasc.dia, nasc.mes, nasc.ano);
}

On Linux, things are a little more complicated since it is necessary to implement a function corresponding to getche().

If there is interest I leave a link to a discussion on the subject: stackoverflow.com/questions/3276546/how-to-implement-getch-Function-of-c-in-linux

Browser other questions tagged

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