sscanf:解析带括号的字符串

sscanf: parsing a string with parentheses

给定以下字符串格式的数据:

"(Saturday) March 25 1989"

我需要解析这个字符串并将每个元素存储在相应的变量中。该变量应包含:

day = 25
year = 1989
day = "Saturday"
month = "March"

我尝试用下面的代码解析字符串,但它似乎不正确。

int day, year;
char weekday[20], month[20], dtm[100];

strcpy( dtm, "(Saturday) March 25 1989" );
sscanf( dtm, "(%s[^)] %s %d  %d", weekday, month, &day, &year );

printf("%s %d, %d = %s\n", month, day, year, weekday );

由于某种原因,代码具有以下输出:

 0, 16 = Saturday)

如有任何帮助,我将不胜感激。

我认为正确的格式应该是这样的:

sscanf( dtm, " (%19[^)]) %19s %d %d", weekday, month, &day, &year );
//            ^  ^     ^   ^
//            |  |     |   limit the number of chars (sizeof month - 1)
//            |  |     the end ) should be matched
//            |  no 's' and limit the number of chars (sizeof weekday - 1)
//            eat whitespaces (like newline)

您混淆了 %s%[,它们是不同的说明符。此外,%[ 不会吃掉停止字符(在本例中为 )),您必须手动完成。

使用 %[,您的 sscanf 调用应如下所示:

sscanf( dtm, "(%[^)]) %s %d  %d", weekday, month, &day, &year );
//                  ^ Eat )
//             ^Scan until )

您还需要处理空格,这样即使像 ( Saturday ) 这样的输入也只会扫描 Saturday:

#define WHITESPACE " \r\n\t\v\f"
sscanf( dtm, " ( %[^)"WHITESPACE"] ) %s %d %d", weekday, month, &day, &year );

而且您还想限制应该为字符串扫描的字符数,这样您就不会遭受缓冲区溢出,但 Ted 的回答已经说明了如何做到这一点。