I have a string called buffer which has the following data stored:
Rb [7, 0] 64
Using sscanf(), I'd like to do the following:
Rb and store it in a string called name7 and store it in an int variable called posx 0 and store it in an int variable called posy 64 and store it in a int variable called battery_level I tried the following, but it doesn't work:
sscanf(buffer, "%s[^\ ] [%d,%d] %d", name, &posx, &posy, &battery_level);
Problems that I see:
"\ " is not a valid escape sequence."%s[^ ]" does not do what you are expecting it to do. You need to use "%[^ ]".You can use
sscanf(buffer, "%s [%d,%d] %d", name, &posx, &posy, &battery_level);
or
sscanf(buffer, "%[^ ] [%d,%d] %d", name, &posx, &posy, &battery_level);
Both of them work. See working code at http://ideone.com/QNuQuY
Hope that it helps you.
I wrote a code, where the inputs will be divided by the first space ' ' sign, you can use other characters also, and improving this logic you can get your desired result:
#include <stdio.h>
int main()
{
char buffer[] = "Rb [7, 0] 64";
int posx, posy, batttery_level
sscanf(buffer, "%[^ ] [%d,%d] %d", name, &posx, &posy, &battery_level);
printf("%s [%d,%d] %d\n", name, posx, posy, battery_level);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With