我有以下代码段:
char s[] = "2012-06-01-02";
int nYear;
int nMonth;
int nDay;
int nPass
sscanf(s, "%d-%d%-%d-%d", &nYear, &nMonth, &nDay, &nPass);
此代码使用Visual Studio按预期工作,但我使用gcc
获得以下编译警告warning: unknown conversion type character '-' in format
然后,如果我运行代码,我得到nYear,nMonth的预期值,但是nDay和nPass都是0.
为什么这不起作用?
答案 0 :(得分:4)
我认为你不想要%-
。删除%
:
sscanf(s, "%d-%d%-%d-%d", &nYear, &nMonth, &nDay, &nPass);
^
|--- delete this '%'
你最终想要的是:
sscanf(s, "%d-%d-%d-%d", &nYear, &nMonth, &nDay, &nPass);
顺便说一下,如果你是初学者,你可能想看看clang。在这种情况下,您将获得更好的错误消息,它将帮助您更快地学习。例如:
example.c:10:22: warning: invalid conversion specifier '-'
[-Wformat-invalid-specifier]
sscanf(s, "%d-%d%-%d", &nYear, &nMonth, &nDay, &nPass);
~^
1 warning generated.