我试图通过调用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). 有什么想法吗?谢谢你的帮助!只需注意:我是一个初学者程序员,但试图完全沉浸在自己,因为我刚刚开始的PhD,主要处理编程,所以我是一个完全的新手。
发布于 2014-03-11 20:43:50
函数localtime为以返回struct tm* (即指向结构的指针)。
您正试图将其赋值给类型为struct tm (注意:其中没有指针)的变量t。
不能将指针赋给非指针。
我建议更改为:
int parse_system_date(struct tm system_date, date * parsed_date) {
struct tm* pt;
[....]
pt = localtime(&ts);现在,我将留给您去查找sscanf的文档,您将告诉我们sscanf的参数#1应该是什么,以及您实际传递的是什么。
发布于 2014-03-11 20:42:48
system_date在main中为char *,在函数调用中为struct tm system_date。将函数调用更改为
int parse_system_date(char *system_date, date * parsed_date)发布于 2014-03-11 20:47:27
正如man localtime所说:
结构tm *localtime(const time_t *timep);
t = localtime(&ts)中的t是一个struct tm而不是struct tm*,而localtime返回一个指针。
第二件事,你并没有向我们展示parsed_date是什么样子的(没有定义date结构)。system_date也是一个struct tm,那么为什么你会期望它在sscanf中被认为是const char*
https://stackoverflow.com/questions/22326046
复制相似问题