This code works:
Code:
#include <stdio.h>
int main()
{
char buffer[500] = "DATA: 3,43,56,32f402,44,57,32f403,45,58,32f404";
char *buf = buffer;
int count;
int pos;
sscanf(buffer, "DATA: %d,%n", &count,&pos); //First Value is Count, get it in a variable.
printf("Count - %d\n", count);
buf+=pos; //strlen("DATA: 3,") = 8
for(int c = 0; c < count; c++)
{
int a1, a2, a3;
sscanf(buf, "%d,%d,%x,%n", &a1, &a2, &a3, &pos);
printf("%d,%d,%x,%d\n", a1, a2, a3, pos);
buf+=pos;
}
return 0;
}
As does this, but it's certainly a bit more complicated:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
void bad_input()
{
printf("could not parse input\n");
exit(1);
}
int main()
{
char buffer[500] = "DATA: 3,43,56,32f402,44,57,32f403,45,58,32f404";
char *buf = buffer;
int count;
int pos;
char *p;
char *after;
p = strchr(buf, ':');
if (!p) bad_input();
buf = p+1;
count = strtol(buf, &after, 10);
printf("Count - %d\n", count);
buf = after+1;
for(int c = 0; c < count; c++)
{
int a1, a2, a3;
assert(*after == ',');
a1 = strtol(buf, &after, 10);
buf = after+1;
assert(*after == ',');
a2 = strtol(buf, &after, 10);
buf = after+1;
assert(*after == ',');
a3 = strtol(buf, &after, 16);
buf = after+1;
printf("%d,%d,%x\n", a1, a2, a3);
}
return 0;
}
Ok, so the latter code does some more error checks, which could help if the input data is "malformed" for any reason.
--
Mats