我正在创建一个函数,它获取一个个人记录(存储在函数参数的*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;
  }

最佳答案

问题是strtok,而不是strrchrstrtok在原始缓冲区中的标记后面放置一个空字节。

关于c - 值返回错误的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21670288/

10-12 02:43