我正在尝试编写一种将代表日期的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可以影响其他变量,或者我应该怎么做才能防止这种情况发生?
最佳答案
把事情简单化:
#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