Issue
This Content is from Stack Overflow. Question asked by jms1980
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 %sn",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?
Solution
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.
This Question was asked in StackOverflow by jms1980 and Answered by DĂșthomhas It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.