【问题标题】:reading from an input line with ""从带有“”的输入行读取
【发布时间】:2021-12-28 17:17:42
【问题描述】:

我有这个程序应该读取一行,例如post "nice job" john,我想获取该行中的每个令牌,但由于某种原因,我只得到其中一些。

预期输出:

post
nice job
john

我的输出:

post
nice

我确定我在 sscanf 上设置了正确的格式,所以我不明白为什么它不会将“好工作”视为一个词。

程序:

#include <stdio.h>

int main()
{
    char token1[128];
    char token2[128];
    char token3[128];
    char str[] = "post \"nice job\" john";
    sscanf(str,"%s \"%s\" %s",token1,token2,token3);
    puts(token1);
    puts(token2);
    puts(token3);
   return(0);
}

【问题讨论】:

  • 如果您尝试sscanf(str,"%s %s %s",token1,token2,token3); 会怎样?
  • 第二个%s 不会读取"nice job",而是在第一个空格字符处停止,因此它只会读取"nice"。使用%[] 格式或fgets()strtok() 会更容易。
  • 为什么这被标记为 C++?这是 C 代码,除了 new(已泄露)。在 C++ 中,这很容易,您可以使用 std::quotedstd::string 和一大堆更好的方法。我不认为应该挽救这个sscanf 代码。
  • 我尝试使用sscanf(str,"%s %s %s",token1,token2,token3);,但就像我说的我不想要“好工作”,我只想要这个短语
  • 我不明白的是为什么当我以单词有“”的格式说时,这是在第一个空白处

标签: c string


【解决方案1】:

第二个%s 读作"nice",因为%s 停在第一个空格处。然后,格式字符串要求匹配 " 引号,这不是下一个(下一个是空格)。 scanf 函数在找到匹配项之前不会跳过输入,它们会停止。始终检查应该是 3 的返回值。

这段代码

#include <stdio.h>
    
int main()
{
    char token1[128] = "";
    char token2[128] = "";
    char token3[128] = "";
    char str[] = "post \"nice job\" john";
    int res = sscanf(str, "%s \"%[^\"]\"%s", token1, token2, token3);
    printf("%d\n", res);
    puts(token1);
    puts(token2);
    puts(token3);
    return(0);
}

输出

3
post
nice job
john

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-08
    • 2014-08-02
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多