If you don't know the order of the data, you can't use sscanf or Salem's method.
I thought this would be a good way to get my brain working this morning, so I wrote a little "state machine" parser. It might seem like overkill or it might be something with some potential depending on the details of the task.
Code:
#include <stdio.h>
#include <stdlib.h>
enum {
ERR,
INT,
FLOAT
};
typedef struct {
union {
int i;
float f;
} value;
int type;
} Number;
#define MAX 8
void getValue (char *raw, int type, Number *data) {
if (type == INT) data->value.i = atoi(raw);
else if (type == FLOAT) data->value.f = strtof(raw, NULL);
data->type = type;
}
int main(void) {
char in[] = "178.50|125|1070", *p = in, *cur = NULL;
int state = INT, count = 0, i;
Number data[MAX];
while (*p && count < MAX) {
if (*p == '|') {
*p = '\0';
if (cur) {
getValue (cur, state, &data[count++]);
cur = NULL;
state = INT;
}
} else if (*p == '.') {
if (state == FLOAT || state == ERR) state = ERR;
else state = FLOAT;
} else if (*p >= '0' && *p <= '9') {
if (!cur) cur = p;
} else state = ERR;
p++;
}
if (cur && count < MAX) getValue (cur, state, &data[count++]);
// output
for (i = 0; i < count; i++) {
switch (data[i].type) {
case ERR:
printf("Bad value in packet!\n");
break;
case INT:
printf("Integer: %d\n", data[i].value.i);
break;
case FLOAT:
printf("Float: %f\n", data[i].value.f);
break;
default:
printf("WTF?\n");
}
}
return 0;
}