Reputation: 139
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 name
7
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);
Upvotes: 4
Views: 3968
Reputation: 488
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;
}
Upvotes: 1
Reputation: 206567
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
Upvotes: 3