cscanfformattedformatted-text

How to extract some formatted string from the buffer using scanf?


I need to extract both "rudolf" and "12" from that long string: "hello, i know that rudolph=12 but it so small..." using scanf, how can I do it?

This buffer can contains any formatted strings like ruby=45 or bomb=1, and I dont know it in advance.

I am trying something like that, but it was unsuccessful

#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;
}

Solution

  • Iterate through the sentence using a temporary pointer and %n to extract each sub-string.
    %n will give the number of characters processed by the scan to that point. Add that to the temporary pointer to advance through the sentence.
    Try to parse from each sub-string the name and value. The scanset %31[^=] will scan a maximum of 31 characters, leaving room in name for a terminating zero. It will scan all characters that are not an =. Then the format string will scan the = and try to scan an integer.

    #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;
    }