我有一个临时字符串: temp =“2014年1月16日01 12 59 OP grs0”;
我想通过使用sscanf()以及任何其他方式从此字符串中检索年,月,日,小时,分钟和秒。
我有一些虚拟代码:
int ret_count = 0;
char discard_msg_type[ENTRY_SIZE]=" "; /* message type is irrelevant */
*hour = *minute = *second = *month = *day = *year = -1 ; /* All these are integer pointers */
ret_count = sscanf(temp,"%d %s %d %s %d %d %d",year,month,
day,discard_msg_type,
hour,minute,second);
执行后我期望ret_count值为7,但它是1。
答案 0 :(得分:0)
格式字符串和数据之间存在类型不匹配问题:
Data: "2014 Jan 16 01 12 59 OP grs0"
Format: "%d %s %d %s %d %d %d"
格式字符串和参数之间也存在类型不匹配问题:
Format: "%d %s %d %s %d %d %d"
Variables: int* int* int* char* int* int* int*
你需要解决这两个问题。例如:
int yy, dd, hh, mm, ss;
char mmm[6];
if (sscanf(temp, "%d %s %d %d %d %d", &yy, mmm, &dd, &hh, &mm, &ss) != 6)
...report format error...
else if ((*month = map_month_name(mmm)) == -1)
...report unrecognized month name...
else
{
*year = yy;
*day = dd;
*hour = hh;
*minute = mm;
*second = ss;
}
map_month_name()
可能在哪里:
int map_month_name(char const *mmm)
{
static char const *months[] =
{
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
for (size_t i = 0; i < sizeof(months)/sizeof(months[0]); i++)
{
if (strcmp(mmm, months[i]) == 0)
return i + 1;
}
return -1;
}