我正在創建一個函數,它將個人記錄(存儲在函數參數中的*individual
中),分離記錄以獲取人員生日,然後函數計算其年齡。我遇到的問題是當我使用strrchr
搜索記錄的生日時,它會在我不想要的時候更改原始值。所以,而不是像它應該存儲Steven, Cortright, 3/1/1940
,它存儲Steven, Cortright, 3
值返回錯誤值
我已經嘗試了一切,我可以想到解決這個問題。下面是我的代碼,我感謝所有幫助/建議:
char* calcage(char *individual)
{
time_t current_time;
char *c_time_string;
char *birthday;
char *bmonth, *bday, *byear;
int numbmonth, numbday, numbyear;
struct tm str_bday;
time_t time_bday;
double diff;
double years;
double monthscalc;
int monthsage;
int yearsage;
current_time = time(NULL);
c_time_string = ctime(¤t_time);
birthday = strrchr(individual, ',');
birthday++;
bmonth = strtok(birthday, "/");
bday = strtok(NULL, "/");
byear = strtok(NULL, "/");
numbmonth = atoi(bmonth);
numbday = atoi(bday);
numbyear = atoi(byear);
str_bday.tm_year = numbyear - 1900;
str_bday.tm_mon = numbmonth - 1;
str_bday.tm_mday = numbday;
str_bday.tm_hour = 0;
str_bday.tm_min = 0;
str_bday.tm_sec = 1;
time_bday = mktime(&str_bday);
diff = difftime(current_time, time_bday);
years = diff/60/60/24/365.242;
yearsage = (int) years;
int inpart = (int) years;
double months = years - inpart;
monthscalc = (365.242 * months)/30.4368;
monthsage = (int) monthscalc;
char *calculatedAge = (char *)malloc(50*sizeof(char));
snprintf(calculatedAge,100, "You are %d years and %d months old.", yearsage, \
monthsage);
return calculatedAge;
}
這是由於函數strtok如描述的修改其參數docs – user3159253