If it is just about extending your sscanf
-approach, then simply add the -+.
-characters, and use datatype float
or double
, which can represent floating point values:
int main() {
char * string = "xx=3300 rr=3.6 zz=-0.8";
float val;
if(sscanf(string, "%*[^-+.0123456789]%f", &val)==1)
printf("%f\n", val);
else
printf("not found\n");
return 0;
}
The better approach would be, however, to first split the string into tokens, e.g. based on the white spaces or the =
-sign, such that you know exactly where you expect a number in the input; then you can convert a string to a number of your choice. Such an approach could look as follows:
int main() {
char string[] = "xx=3300 rr=3.6 zz=-0.8";
char *pair = strtok(string," ");
while (pair) {
char *beginOfVal = strchr(pair, '=');
if (beginOfVal) {
beginOfVal++;
char *endOfVal;
double val = strtod(beginOfVal, &endOfVal);
if (endOfVal==beginOfVal) {
printf("error scanning %s as a number.\n", beginOfVal);
}
else {
printf("val: %lf\n", val);
}
}
pair = strtok(NULL," ");
}
}