为什么 sscanf 不读取格式字符串中的第一个参数?

Why is sscanf not reading the first argument in the format string?

在下面的程序中,格式字符串中除了第一个值(月份)之外的所有内容都被读入 SYSTEMTIME 结构。谁能帮我解决这个问题?

#include <Windows.h>
#include <stdio.h>

int main()
{
    SYSTEMTIME st;
    char buf[50];
    strcpy(buf, "6/23/2015 12:00:00");
    sscanf(buf, "%d/%d/%d %d:%d:%d", &st.wMonth, &st.wDay, &st.wYear, &st.wHour, &st.wMinute, &st.wSecond);
    printf("%d %d %d %d %d %d\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
    return 0;
}

程序的输出是:

2015 0 23 12 0 0

应该是:

2015 6 23 12 0 0

您使用了错误的格式说明符。 %d 用于 ints。 st.*int 吗?号

根据the documentationSYSTEMTIME结构定义为

typedef struct _SYSTEMTIME {
  WORD wYear;
  WORD wMonth;
  WORD wDayOfWeek;
  WORD wDay;
  WORD wHour;
  WORD wMinute;
  WORD wSecond;
  WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;

现在,WORD 是什么?

引用自here,

WORD

A 16-bit unsigned integer. The range is 0 through 65535 decimal.

This type is declared in WinDef.h as follows:

typedef unsigned short WORD;

所以,WORD(st.*) 是一个 unsigned shortunsigned short 的正确格式说明符是 %hu。根据标准 (n1570),使用错误的格式说明符会导致 Undefined Behavior

7.21.6.2 The fscanf function

[...]

  1. If a conversion specification is invalid, the behavior is undefined. 287)