【问题标题】:How can I use sscanf to read a string between brackets?如何使用 sscanf 读取括号之间的字符串?
【发布时间】:2012-03-30 11:21:30
【问题描述】:

我有一些代码读取文本文件并扫描括号中的单词:'[' 和 ']'。

当我找到以 '[' 开头的行时,我读取了字符串:

line[64] = "[word]";
sscanf(line, "[%s]", resource);

printf("%s\n",resource);

==> word]

但我总是以字符串+括号结束。如何格式化 sscanf 以仅读取末尾没有括号的字符串?

【问题讨论】:

    标签: c linux gcc scanf


    【解决方案1】:

    scanf() 读取的字符集中排除]

    char resource[100];
    if (sscanf(line, "[%99[^]]]", resource) != 1) /* error */;
    
    /* same as */
    if (sscanf(line, "[" "%99[^]]" "]", resource) != 1) /* error */;
    /*          literal   scanset   literal */
    

    【讨论】:

    • 谢谢。我还尝试使用 [a-z] 定义的字符集,但无法使其工作。
    • 我不太喜欢格式化字符串,但它不会是%99s吗?如果你能解释这一点,最好是参考标准,你肯定会得到我的支持。
    • @Gandaro:您的示例在输入(“[word]”)中留下了关闭的] 未解释。假设需求更改为从 "[foo] [bar]" 中读取两个单词 ...
    • @phresnel: "%99s"[] 读入变量。 "%s" 转换只跳过空格。
    • @fazineroso:sscanf(line, "[%[a-z]]", resource) 也应该可以。你可能做错了什么......
    猜你喜欢
    • 2016-08-14
    • 2021-11-18
    • 1970-01-01
    • 2013-02-04
    • 2021-05-25
    • 2016-03-24
    • 2023-03-10
    • 2013-02-28
    相关资源
    最近更新 更多