Home > Software design >  How do I separate 4.8 and meters from 4.8meters in C
How do I separate 4.8 and meters from 4.8meters in C

Time:02-04

I have 4.8meters I want to put 4.8 in a float variable and meters in string. I wanted to do it using strtok() but wasn't able to.

CodePudding user response:

You can use strtod to parse the floating point number and set a pointer to the rest of the string:

      char str[] = "4.8meters";
      char *p;
      double x = strtod(str, &p);

      if (p == str) {
          printf("error: no number to parse\n");
      } else {
          printf("x=%f  unit=%s\n", x, p);
      }

Output: x=4.800000 unit=meters

CodePudding user response:

Another way to do this sort of thing is with sscanf:

char *str = "4.8meters";
float f;
char unit[10];

int n = sscanf(str, "%f%9s", &f, unit);

if(n == 2)
     printf("number: %f, unit: %s\n", f, unit);
else if(n == 1)
     printf("number: %f (no unit)\n", f);
else printf("invalid input\n");

A couple things to note here:

  1. As for any member of the scanf family, it's vital to check the return value, to see if all expected items were parsed. In this case, the code is written so that it can tolerate the case where the unit string is missing.
  2. As it happens, using scanf in this way, it will equally accept "4.8meters" or "4.8 meters" — that is, whitespace is optional between the number and the string.
  3. There's a limit on how long the unit string can be -— in this case, 9 characters.
  •  Tags:  
  • Related