我试图通过调用 struct tm 并获取当前时间来解析系统日期,然后再解析为单独的日、月、年。这是我此时的代码:
/* Parses a system date structure 'system_date' into a structure date 'parsed_date'.*/
int parse_system_date(struct tm system_date, date * parsed_date) {
time_t ts;
struct tm t;
ts = time(NULL);
t = localtime(&ts);
/* scan the year, month and year from the input string*/
//printf("Current Date: %d/%d/%d\n",
// current_time->tm_mday, current_time->tm_mon + 1, current_time->tm_year + 1900);
const int ret = sscanf(system_date, "%d/%d/%d",
&parsed_date->(tm_mday),
&parsed_date->(tm_month + 1),
&parsed_date->(tm_year + 1900));
return ret;
}
它被主函数调用:
struct tm t;
char system_date[20];
fgets(system_date, 20, stdin);
parse_system_date(system_date, &t);
printf("Today's date is: %s\ndd = %d, mm = %d, yy = %d\n", system_date, t.tm_mday, t.tm_mon, t.tm_year);
我收到错误:
date.h:30: error: incompatible types in assignment
行中:
t = localtime(&ts);
并且:
date.h:39: error: incompatible type for argument 1 of ‘sscanf’
对于行:
&parsed_date->(tm_mday).
有什么想法吗?谢谢您的帮助!请注意:我是一名初学者程序员,但我试图完全沉浸在其中,因为我刚刚开始攻读主要研究编程的博士学位,所以我是一个完全的新手。
最佳答案
函数本地时间
是documented返回一个struct tm*
(即指向结构的指针)。
您正在尝试将其分配给变量t
,该变量的类型为struct tm
(注意:其中没有指针)。
不能将指针分配给非指针。
我建议更改为:
int parse_system_date(struct tm system_date, date * parsed_date) {
struct tm* pt;
[....]
pt = localtime(&ts);
<小时/>
现在我将让您查找 sscanf
的文档,然后您告诉我们 sscanf
的参数 #1 应该是什么,以及您要做什么实际上正在通过。
关于c - 分配时不兼容的类型 - 系统日期的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22326046/