Change the date format in multi dimensional array

Viewed 42

I have a multi dimensional array which contains some info, in the same array there is a date, but I want to change the format of the date from :

YYYY-MM-DD

to

DD-MM-YYYY

I tried to access the elements of the array using nested loops, but as I reach the format I get confused.

Here is my code :

#include<stdio.h>
#include<string.h>
typedef struct studentStruct {
 char id[10];
 char name[50];
 char ddmmyyyy[11];
 char cityBirth[20];
}Student;
void fillStruct(Student *std, char currentStd[4][50]);
int main(){
 char records[3][4][50] = {
 {"17581726", "Mohammad Alabdullah", "2002-12-10", "Buriydah"},
 {"55382214", "Ibrahim Alfaris", "2003-05-07", "Riyadh"},
 {"62111622","Ahmad Almansor","2001-02-22","Buriydah"}
 };
34
 Student students[3];
 for(int i=0;i<3;i++) fillStruct(&students[i], records[i]);
 for (int i = 0; i < 3; i++) {
 printf("Student Name: %s, ",students[i].name);
 printf("Student ID: %s, ",students[i].id);
 printf("DOB: %s, ",students[i].ddmmyyyy);
 printf("City of DOB: %s\n",students[i].cityBirth);
 }
}
1 Answers

Use scanf



 void changeFormat(const size_t rows, const size_t cols, const size_t chars, char (*array)[cols][chars], size_t dateindex)
 {
     int y,m,d;

     for(size_t row = 0; row < rows; row++)
     {
         if(sscanf(array[row][dateindex], "%d-%d-%d", &y, &m, &d) != 3) {/* handle error */}
         snprintf(array[row][dateindex], chars, "%02d-%02d-%d", d, m, y);
     }
 }

 void printTable(const size_t rows, const size_t cols, const size_t chars, char (*array)[cols][chars])
 {
    for(size_t row = 0; row < rows; row++)
    {
        for(size_t col = 0; col < cols; col++)
        {
            printf("%s%s", array[row][col], (col == cols-1) ? "" : ", ");
        }
        printf("\n");
    }
 }
 

 int main(void)
 {
     char records[][4][50] = {
     {"17581726", "Mohammad Alabdullah", "2002-12-10", "Buriydah"},
     {"55382214", "Ibrahim Alfaris", "2003-05-07", "Riyadh"},
     {"62111622","Ahmad Almansor","2001-02-22","Buriydah"}
     };

    printTable(3,4,50, records);
    changeFormat(3,4,50, records, 2);
    printf("--------------------\n");
    printTable(3,4,50, records);
}

https://godbolt.org/z/hEzzsM6YP

Related