【发布时间】:2021-11-23 12:31:48
【问题描述】:
我正在尝试从给我的日期中提取日期、月份和年份作为字符串。我在乞讨时将它们作为子字符串,然后我试图将它们转换为整数类型。第一个整数被成功提取,但第二个和第三个接收到错误的值。 Atoi 保留旧的转换值并将新值附加到它们
这是我的代码:
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);
【问题讨论】:
-
您的数组大小不足以容纳终止的空字节。
-
而且
strncpy在所有情况下都不会终止。 -
在处理日期时考虑
strptime。