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;
}
Iterate through the sentence using a temporary pointer and
%nto extract each sub-string.%nwill 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 innamefor 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.