如何使用 scanf 从缓冲区中提取一些格式化字符串?

bon*_*tit 1 c scanf formatted formatted-text

我需要从那个长字符串中提取“rudolf”“12”"hello, i know that rudolph=12 but it so small..." :使用scanf,我该怎么做?

该缓冲区可以包含任何格式化字符串,例如ruby=45bomb=1,但我事先并不知道。

我正在尝试类似的事情,但没有成功

#include <stdio.h>

int main()
{
    char sentence[] = "hello, i know that rudolph=12 but it so small...";
    char name[32];
    int value;

    sscanf(sentence, "%[a-z]=%d", name, &value);
    printf("%s -> %d\n", name, value);

    getchar();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

use*_*023 5

使用临时指针迭代句子并%n提取每个子字符串。
%n将给出扫描到该点处理的字符数。将其添加到临时指针以前进到句子中。
尝试从每个子字符串中解析名称和值。扫描集%31[^=]将扫描最多 31 个字符,并name为终止零留出空间。它将扫描所有非=. 然后格式字符串将扫描=并尝试扫描整数。

#include <stdio.h>
#include <stdlib.h>

int main (void) {
    char sentence[] = "hello, i know that rudolph=12 but it so small...";
    char string[sizeof sentence] = "";
    char name[32] = "";
    char *temp = sentence;
    int value = 0;
    int count = 0;
    int parsed = 0;

    while (1 == sscanf(temp, "%s%n", string, &count)) {
        temp += count;
        if (2 == sscanf(string, "%31[^=]=%d", name, &value)) {
            parsed = 1;
            break;
        }
    }
    if (parsed) {
        printf("%s %d\n", name, value);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)