我正在尝试编写一种方法,将表示日期的C字符串转换为其他格式。
/*
Takes in a date of the format MM/DD/YYYY-HR:MN,
and converts it to YYYYDDMMHRMN format.
*/
void convertFormattedDate(char** date){
char* dateHelper = calloc(strlen(*date), sizeof(char));
strcpy(dateHelper, *date);
const char * delims = "/-:";
char* formattedDate = calloc(12+1, sizeof(char)); //leaving space for null terminator
char* token = strtok(dateHelper, delims);
//yes I know this is hacky and terrible
char* month = NULL;
char* day = NULL;
char* year = NULL;
char* hr = NULL;
char* mn = NULL;
int index=0;
while (token!=NULL) {
switch (index) {
case 0:
month = token;
break;
case 1:
day = token;
break;
case 2:
year = token;
break;
case 3:
hr = token;
break;
case 4:
mn = token;
break;
default:
printf("Something weird has happened");
break;
}
token = strtok(NULL, delims);
index++;
}
strcat(formattedDate, year);
strcat(formattedDate, month);
strcat(formattedDate, day);
strcat(formattedDate, hr);
strcat(formattedDate, mn);
*date = formattedDate;
}
当我试着打电话时
char* date = "10/24/1994-23:14";
convertFormattedDate(&date);
在我开始将年,月,日等连接到格式化日期之前,一切正常。
我打电话后 strcat(formattedDate,year);
并逐步执行我的代码,mn的值突然变为
141994
什么时候应该只是
14
有谁知道为什么调用strcat会影响其他变量,或者我应该做些什么来防止这种情况?
答案 0 :(得分:1)
保持简单:
#include <stdio.h>
#include <string.h>
/*
Takes in a date of the format MM/DD/YYYY-HR:MN,
and converts it to YYYYDDMMHRMN format.
*/
void convertFormattedDate(char* date){
char* dateHelper = strdup(date);
dateHelper[0] = date[6];
dateHelper[1] = date[7];
dateHelper[2] = date[8];
dateHelper[3] = date[9];
dateHelper[4] = date[3];
dateHelper[5] = date[4];
dateHelper[6] = date[0];
dateHelper[7] = date[1];
dateHelper[8] = date[11];
dateHelper[9] = date[12];
dateHelper[10] = date[14];
dateHelper[11] = date[15];
dateHelper[12] = '\0';
strcpy(date, dateHelper);
free(dateHelper);
}
int main(void)
{
char dt[] = "10/21/2015-00:19";
convertFormattedDate(dt);
printf("%s\n", dt);
return 0;
}
节目输出
201521100019