I am trying to extract day, month, and year from a date given for me as a string. I took them as a substring at the begging then I am trying to convert them to the integer type. The first integer is extracted successfully but the second and the third are receiving wrong values. Atoi keeps the old values of conversion and append the new value to them
This is my code :
char day[2], month[2], year[4];
strncpy(day, date, 2);
strncpy(month, &date[3], 2);
strncpy(year, &date[6], 4);
int dayInt = atoi(day);
int monthInt = atoi(month);
int yearInt = atoi(year);
These are the values stored in the variables:
CodePudding user response:
You don't have terminating null bytes in your strings.
char day[3], month[3], year[5];
strncpy(day, date, 2);
day[2] = '\0';
strncpy(month, &date[3], 2);
month[2] = '\0';
strncpy(year, &date[6], 4);
year[4] = '\0';
int dayInt = atoi(day);
int monthInt = atoi(month);
int yearInt = atoi(year);
But you could do it more simply using sscanf()
.
sscanf(date, "-/-/M", &dayInt, &monthInt, &yearInt);
Replace /
in the format string with your actual delimiter if necessary.
CodePudding user response:
Although you can use atoi
to do the conversions, it would be cleaner to use sscanf
. Even better would be to use strptime
.
#include <stdio.h>
#include <time.h>
int
main(void)
{
char *date = "20210210";
int day, month, year;
struct tm tm = {0};
char *end = "";
if( sscanf(date, "M--", &year, &month, &day) == 3 ){
printf("year: %d, month: %d, day: %d\n", year, month, day);
}
end = strptime(date, "%Y%m%d", &tm);
if( end != NULL ){
year = tm.tm_year 1900; /* tm_year is offset from 1900 */
day = tm.tm_mday;
month = tm.tm_mon 1; /* tm_mon is 0 to 11 */
printf("year: %d, month: %d, day: %d\n", year, month, day);
}
return 0;
}