在 c 中的 sscanf 中选择格式

Choose formats in sscanf in c

我正在尝试使用 c 语言中的 sscanf() 解析字符串 Connected to a:b:c:d completed (reauth) id=5

我的格式字符串是 Connected to %s completed %s id=%s。但在某些情况下,我的字符串是 Connected to a:b:c:d completed id=5。我没有得到 reauth 部分。

我可以使用两个 sscanf() 调用。但我需要使用单个 sscanf() 调用。有没有办法根据 sscanf() 中的某些条件选择格式?

我正在尝试使用的示例代码

#include<stdio.h>
int main() {
        char* string="Connected to a:b:c:d completed (auth) id=3";
        char* fmt = "Connected to %s completed id=%d";
        char b[60]={0};
        int id = -1;

        sscanf(string, fmt, b, &id);

        printf("Auth :: %s :: id :: %d\n", b, id);
}

是的,这是可能的。使用第一个 format 字符串检查 sscanf() 的 return 值。如果它不等于预期的数字,请使用 sscanf().

的其他格式字符串

P.S。 - 我假设你有 只有 两种格式,可以以 或者 的方式出现。


编辑:

如果您想要一种更灵活、更健壮和 圆滑 的方法,并且如果您能够 放弃 使用 sscanf(),你可以利用 strtok 根据某些 delimters tokenize 你的字符串,并从中获取所需的值输入字符串。

#include<stdio.h>
int main() {
   char* string1="Connected to a:b:c:d1 completed id=1";
   char* string2="Connected to a:b:c:d2 completed (auth) id=3";

   char* fmt = "Connected to %s %*[^=]=%d";
   char b[60]={0};
   int id = -1;

   n=sscanf(string1, fmt, b, &id);
   printf("Auth :: %s :: id :: %d - %d\n", b, id,n);

   n=sscanf(string2, fmt, b, &id);
   printf("Auth :: %s :: id :: %d - %d\n", b, id,n);
}

其中:

  • %[^=] 将消耗非“=”字符的非空字符串
  • %*...会丢弃通讯组(略过)

如前所述,我们应该分析 sscanf return 值 if(sscanf ...==2)