Search code examples
cdateintegerscanfc-strings

converting date string to int


I want to convert a date string to int.

char date1[20], date2[20];
    
int day1, month1, year1, day2, month2, year2;
    
printf("Enter the first date in the format dd-mm-yyyy: ");
scanf("%s", date1);
    
printf("Enter the second date in the format dd-mm-yyyy: ");
scanf("%s", date2);

Then I want to store the corresponding values in day1, month1, year1, day2, month2, year2 int variables. Input is taken in string format as (dd-mm-yyyy) format. I need to extract dd from string and store in day1, mm from string and store in month1 and extract yyyy from string and store in year1. Same follows for 2nd date that is date2. How do I do it?

Requesting help!!


Solution

  • u can use ptr

    char *ptr = date1;
    char day1_c[10] = {0x00,};
    char month1_c[10] = {0x00,};
    char year1_c[10] = {0x00,};
    
    strncpy(day1, ptr, 2);
    strncpy(month1, ptr+3, 2);
    strncpy(year1, ptr+6, 4);
    
    int day1 = atoi(day1_c);
    int mont1 = atoi(month1_c);
    int year1 = atoi(year1_c);