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
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);
}
Why are you capturing the date on a
int
? This is clearly a case of catching her in achar[9]
and then manipulate the string, unless it’s part of a challenge, what you’re doing makes no sense.– Andre