No that’s not really a good way. If you just want the numbers a numbers, i.e. as normal int
values, then use the "%d"
conversion operator instead, and have your variables be normal int
variables, which you then pass to sscanf
using the address-of operator &
. As in
int num1;
int num2;
int num3;
int num4;
sscanf(str, "B%d,B%d,B%d,B%d", &num1, &num2, &num3, &num4);
If you on the other hand want the digits as strings, then use array instead of pointers:
char num1[2]; // Two characters is enough for a single-character string, plus terminator
char num2[2];
char num3[2];
char num4[2];
sscanf(str, "B%1s,B%1s,B%1s,B%1s", num1, num2, num3, num4);
The format "%1s"
tells sscanf
to only read a signle character.
Besides that, you should probably make sure that the sscanf
call actually parsed the input correctly. This can be done by checking what sscanf
returns:
if (sscanf(str, "B%d,B%d,B%d,B%d", &num1, &num2, &num3, &num4) == 4)
{
// All okay
}
else
{
// Something went wrong
}
1
solved C – Separating string using other delimiters?