【问题标题】:sscanf: parsing a string with parenthesessscanf:解析带括号的字符串
【发布时间】:2021-11-18 13:41:34
【问题描述】:

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

"(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)

我将不胜感激。

【问题讨论】:

    标签: c scanf


    【解决方案1】:

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

    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)
    

    【讨论】:

      【解决方案2】:

      您混淆了 %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 的回答已经说明了如何做到这一点。

      【讨论】:

        猜你喜欢
        • 2020-07-03
        • 1970-01-01
        • 2013-03-21
        • 1970-01-01
        • 1970-01-01
        • 2015-04-10
        • 2020-04-28
        • 1970-01-01
        • 2014-05-20
        相关资源
        最近更新 更多