【问题标题】:C sscanf exact lengthC sscanf 精确长度
【发布时间】:2011-02-13 06:46:00
【问题描述】:

我在使用 sscanf 中的确切字符串长度、%Ns、格式修饰符时遇到问题。当 buff 包含 O 5 hello R 700 时,代码工作正常。但是当我尝试在名称字段中有一个空格时它不起作用。即,当 buff 包含 O 6 h ello R 700 时,它会失败。它使name 包含“h”并且标志包含“ello”而不是 name 包含“hello”

// buff will contain something in the format of "O <name_length> <name> <flags> <mode>"

int namelen;
char name[BUFFSIZE];
char flags[BUFFSIZE];
char mode[20];

sscanf(buff, "O %d", &namelen);

char extractor[BUFFSIZE];
sprintf(extractor, "O %%d %%%ds %%s %%s", namelen);

sscanf(buff, extractor, &namelen, name, flags, mode);

【问题讨论】:

    标签: c scanf


    【解决方案1】:

    %s 仅匹配非空格。你想要%[…],或者更好的是%c(不过请注意自己添加尾随NUL)。

    另外,%*d 会扫描一个数字,但保存它,我想你会更喜欢这样(因为你之前已经得到了namelen)。

    但总的来说,我可能会避免在运行时生成格式字符串。

    int namelen, offset;
    char name[BUFFSIZE];
    char flags[BUFFSIZE];
    char mode[20];
    
    sscanf(buff, "O %d %n", &namelen, &offset);
    memcpy(name, buff + offset, namelen);
    name[namelen + 1] = '\0';
    sscanf(buff + offset + namelen, " %s %s", flags, mode);
    

    (未经测试,但类似的东西应该可以。)

    【讨论】:

    • 不错。我所要做的只是将name[namelen + 1] 更改为name[namelen],而且效果很好。你教会了我 %*d 和 %n。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2022-01-09
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    相关资源
    最近更新 更多