How to convert DDMMAYY to DD/MM/YYYY in C

Asked

Viewed 48 times

-4

#include <stdio.h>
// tetando ex 01 

int main(){
 int dia,mes,ano, data;
  printf("Digite a data em DDMMAAA: ");
  scanf("%d", &data );
  
  dia= data/1000000;
  printf("%d", dia);
 
  
}

I can’t develop the logic to separate month and year from the DDMMAAA format someone can give me some hint, I also searched in the machine to understand if there was any formula but I’m not getting.

  • Why are you capturing the date on a int? This is clearly a case of catching her in a char[9] and then manipulate the string, unless it’s part of a challenge, what you’re doing makes no sense.

1 answer

2

You can do it using only math:

#include <stdio.h>

int main() {
    int data;
    printf("Digite a data em DDMMAAAA: ");
    scanf("%d", &data);
  
    int dia = (data / 1000000) % 100;
    int mes = (data / 10000) % 100;
    int ano = data % 10000;
    printf("A data em DD/MM/AAAA é %02d/%02d/%04d.\n", dia, mes, ano);
}

Read

  • data divided by 10ª as "return data without the last n digits"; and

  • data module 10Šo as "return data only with the last n digits".

Assuming the value entered by the user was 01082021, in the case of mes, for example: when I do 01082021 / 10000, I say remove the last four digits of 01082021, getting 0108. Then when do I 0108 % 100, I say keep the last two digits of 0108, getting 08, which is the month of the date inserted.


Or, how @user140828 noticed but did not detail, store in a char[9]:

#include <stdio.h>
#include <string.h>

int main() {
    char data[9];
    printf("Digite a data em DDMMAAAA: ");
    scanf("%s", data);
    
    char dia[3]; strncpy(dia, data, 2); dia[2] = '\0';
    char mes[3]; strncpy(mes, data + 2, 2); mes[2] = '\0';
    char ano[5]; strncpy(ano, data + 4, 4); ano[4] = '\0';
    printf("A data em DD/MM/AAAA é %s/%s/%s.\n", dia, mes, ano);
}

However, the day, month and year will be as strings. If you want to turn them into integers to manipulate them later, use the function atoi:

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

int main() {
    char data[9];
    printf("Digite a data em DDMMAAAA: ");
    scanf("%s", data);
    
    char diaStr[3]; strncpy(diaStr, data, 2); diaStr[2] = '\0';
    char mesStr[3]; strncpy(mesStr, data + 2, 2); mesStr[2] = '\0';
    char anoStr[5]; strncpy(anoStr, data + 4, 4); anoStr[4] = '\0';
    
    int dia = atoi(diaStr);
    int mes = atoi(mesStr);
    int ano = atoi(anoStr);
    printf("A data em DD/MM/AAAA é %02d/%02d/%04d.\n", dia, mes, ano);
}
  • 1

    Thank you very much!! it was very clear in the explanation, I bugged so much that I could not think of using module, it was so simple kkkkk dscp the question kind silly and again thank you for the help and the explanation.

Browser other questions tagged

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