避免 sscanf 格式问题:

sscanf format trouble avoiding :

我必须拆分 (使用 sscanf yes 或 yes) 一个 char* 格式如下:

First_Line1: This is the 1st line 要么 First_Line: This-is_the_first-line123

我只需要将内容放在2个变量中,一个是“:”之前的内容,另一个是“:”之后的内容。

请注意“:”前后可能有数字和特殊字符。

到目前为止我尝试过的一些例子是:

sscanf(cab, "%[a-zA-Z]%*[:] %[a-zA-Z]", &cab.name, &cab.value);
sscanf(cab, "%s %*[:] %s", &cab.name, &cab.value);

还有很多我不记得了。 (其实我不关心特殊字符,只是想把它一分为二)

我无法使用任何格式参数使其正常工作。请帮忙。谢谢

我以前从未使用过这种格式,但我很快就弄明白了:

#include <stdio.h>

int main(void)
{
    char inp [] = "one two: three four";
    char str1[100] = "";
    char sep = ' ';
    char str2[100] = "";

    if (sscanf(inp, "%[^:]%c %[^[=10=]]", str1, &sep, str2) != 3)
        return 1;

    printf("'%s'\n", str1);
    printf("'%s'\n", str2);
    return 0;
}

程序输出(添加'以清楚显示字符串的范围):

'one two'
'three four'

请注意您的一个特定错误:&cab.name 等不应该有 &,因为您提供的值要么是指针,要么衰减到指针。

编辑:

正如@user3121023 所指出的(删除后的评论),格式%[^[=16=]] 将过早地终止格式字符串。所以我建议使用输入数据中没有出现的字符。由于从未找到,因此采用其余输入。

if (sscanf(inp, "%[^:]%c %[^]", str1, &sep, str2) != 3)
    return 1;