2014-02-10 134 views
0

我正在創建一個函數,它將個人記錄(存儲在函數參數中的*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(&current_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; 
    } 
+1

這是由於函數strtok如描述的修改其參數docs – user3159253

回答

2

問題是strtok,不strrchrstrtok在原始緩衝區中的令牌之後放置空字節。

1

相反的strtok使用的sscanf的解析字符串:

int month = 0, day = 0, year = 0; 
sscanf(birthday, "%d/%d/%d", &month, &day, &year); 

這樣,你不要弄亂的說法

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; 
} 
+0

非常感謝你。當我在這裏發佈之前試圖複製它時,iI嘗試使用strcpy,不知道有關strdup。感謝您的幫助 – Stc5097