gpt4 book ai didi

c - 尝试在 struct tm 中设置值

转载 作者:行者123 更新时间:2023-11-30 15:38:48 25 4
gpt4 key购买 nike

我正在尝试创建一个函数来获取当前日期、获取个人生日并计算他们的年龄。我得到了当前日期。现在我尝试获取该人的生日(通过 individual 传递给函数)并将该人的生日值存储在名为 str_bday 的 struct tm 变量中。该程序编译,但当我运行它时,我得到这个:

       Your last name is Smith
Sat Feb 8 16:04:05 2014
Your birthday is: 3/1/1940
Wed Dec 31 18:59:59 1969
v245-2%

我不明白为什么当我打印出 str_bday struct tm 变量时,它会打印出他们的生日是 1969 年。有人能帮帮我吗。以下是我的此功能的代码:

       char* calcage(char *individual, char *age)
{

time_t current_time;
char *c_time_string;

current_time = time(NULL);


c_time_string = ctime(&current_time);

printf(c_time_string);



char *birthday = (char *)malloc(50*sizeof(char));
birthday = strrchr(individual, ',');
birthday++;

printf("Your birthday is: %s\n", birthday);


char *bmonth, *bday, *byear;
int numbmonth, numbday, numbyear;


bmonth = strtok(birthday, "/");
bday = strtok(NULL, "/");
byear = strtok(NULL, "/");

numbmonth = atoi(bmonth);
numbday = atoi(bday);
numbyear = atoi(byear);


struct tm str_bday;
time_t time_bday;

str_bday.tm_year = 2012;

time_bday = mktime(&str_bday);
printf(ctime(&time_bday));



}

最佳答案

tm_year 将根据 1900 设置年份。 (例如str_bday.tm_year = numbyear -1900;)

还应按如下方式检查mktime的返回值。

if(time_bday == (time_t)-1)
printf("error");

如果早于一年,它会返回错误,因为它在许多系统上基于 1970 年。

如果是这样的话,必须自当日起进行处理。

<小时/>

测试代码

#include <stdio.h>
#include <time.h>
int main(){
struct tm str_bday = {0};
time_t time_bday;

str_bday.tm_year = 2012 - 1900;
str_bday.tm_mon = 3 - 1;
str_bday.tm_mday = 1;
time_bday = mktime(&str_bday);
if(time_bday == (time_t)-1)
printf("error\n");
else
printf("%s\n", ctime(&time_bday));//Thu Mar 01 00:00:00 2012
return 0;
}

关于c - 尝试在 struct tm 中设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21651904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com