Home > OS >  parsing a date string in YYYYMMDDHH format using sscanf in c programing
parsing a date string in YYYYMMDDHH format using sscanf in c programing

Time:09-19

I have a date string in format YYYYMMDDHH that I am trying to split into year YYYY month MM day DD, and hour HH.

Below is my code in which I am attempting to do this:

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

int main()
{
    char datetime[10];
    char year;
    char month;
    char day;
    char hour;

    sprintf(datetime,"2022092300");
    sscanf(datetime,"%4s%2s%2s%2s",year,month,day,hour);
    printf("year is %s month is %s\n",year,month);

}

Unfortunately this code is not giving me a value for year and month and I doubt it would for day and hour. How do I tweak this code to get the desired results parsing the string into YYYYMMDDHH into YYYY, MM, DD, HH?

CodePudding user response:

When reading strings, you must pass the address of a string as argument.

Also, strings must be terminated with a null (zero) character value. So if you expect a string to hold 10 characters, it must be 11 characters long to include the null terminator.

#include <stdio.h>

int main(void)
{
    char datetime[11];
    char year[5];
    char month[3];
    char day[3];
    char hour[3];

    sprintf(datetime,"2022092300");
    sscanf(datetime,"%4s%2s%2s%2s",year,month,day,hour);
    printf("year is %s month is %s\n",year,month);
}

EDIT

I meant to mention this, but forgot. You should turn your compiler warnings up to at least -Wall -Wextra -pedantic-errors if using GCC or Clang or /W3 if using MSVC. If you are using an IDE you will need to use Google to find how to adjust the compiler error/warning level for that IDE.

CodePudding user response:

You need to use strings for each of the fields so your types are wrong, also you need to ensure space for the '\0' terminator. Introducing constants to ensure your types matches your format format string.

#include <stdio.h>

#define YEAR_LEN 4
#define MONTH_LEN 2
#define DAY_LEN 2
#define HOUR_LEN 2

#define str(s) str2(s)
#define str2(s) #s

int main() {
    char datetime[10 1];
    char year[YEAR_LEN 1];
    char month[MONTH_LEN 1];
    char day[DAY_LEN 1];
    char hour[HOUR_LEN 1];
    sprintf(datetime, "2022092300");
    sscanf(datetime, "%" str(YEAR_LEN) "s%" str(MONTH_LEN) "s%" str(DAY_LEN) "s%" str(HOUR_LEN) "s",year,month,day,hour);
    printf("year is %s month is %s\n",year,month);
}
  • Related