我正在创建一个函数,它接受个人记录(存储在函数参数中的*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;
}
答案 0 :(得分:2)
问题是strtok
,而不是strrchr
。 strtok
在原始缓冲区中的标记之后放置一个空字节。
答案 1 :(得分:1)
而不是strtok使用sscanf来解析字符串:
int month = 0, day = 0, year = 0;
sscanf( birthday, "%d/%d/%d", &month, &day, &year );
这样你就不会搞砸论证
答案 2 :(得分:0)
char* calcage(char *individual){
time_t now = time(NULL);
struct tm *local = localtime(&now);
char *temp = strdup(strrchr(individual, ',')+1);//make copy
char *birthday = temp;
int bmonth, bday, byear;
bmonth = atoi(strtok(temp, "/"));
bday = atoi(strtok(NULL, "/"));
byear = atoi(strtok(NULL, "/"));
int age = local->tm_year + 1900 - byear -1;
int lm = local->tm_mon + 1;
if(bmonth <= lm && bday <= local->tm_mday)
++age;
int mtemp = lm - bmonth;
if(mtemp < 0 || mtemp == 0 && bday > local->tm_mday)
mtemp += 12;
int mage = age * 12 + mtemp;
char *calculatedAge = realloc(temp, 50);
snprintf(calculatedAge, 50, "You are %d years and %d months old.", age, mage);
return calculatedAge;
}