Best way to parse a string of numbers into a float array?

Let's say I have a string of numbers separated by spaces.. for example: "0.002 0.282 0.852 0.285 0.335 0.867".

What's the best way to store these numbers into a float array (if at all possible)? For what it's worth, the string will always consist of 6 numbers with a value between 0 and 1.

Thanks! :D

I'm not sure I can tell you the BEST way to do it, [u]but if you can tell me how you get the string "0.002" to a float[/u], then you can make use of indexOf() in combination with a loop that you can break after it returns -1 and you get the last float.

I [u]think[/u] you'd need to create a float array with sufficient elements, even though you possibly don't know how much they'll be (make a guess with sufficient safety margin).

The examples provided through the link above can get you there rather easily.


footswitch: but if you can tell me how you get the string "0.002" to a float

Use atof() (stands for ascii to float)


1) If I don't pad the string with an extra word, the strtok function leaves out the first number in my string. (not reallly a big deal since the simple solution was to add an extra "term" in front of the original string

Wrong solution.

  tokenPtr = strtok(buffer, " ");
  while( tokenPtr != NULL ) {
    int i = 0;
    tokenPtr = strtok( NULL, " ");
    stringOutput[i] = (String)tokenPtr;

You're stomping on the pointer to the first token before you copy/store it. Don't do that.

Try this, which also defines and increments i properly.

  int i = 0;
  tokenPtr = strtok(buffer, " ");
  while( tokenPtr != NULL )
    stringOutput[i++] = (String)tokenPtr;
    tokenPtr = strtok( NULL, " ");

2) It gives me the error "cannot convert 'float*' to 'float' in return. From what I've gathered, this is because I used a character pointer variable (?? correct me if I'm wrong), so the function must return a pointer float array, not a regular array.

You can't return a pointer to an array defined in the function. The array goes out of scope when the function ends. A pointer to out-of-scope memory is a bad thing.

Make the array global, or pass it to the function to fill.

3) If I change the function type to float*, the script compiles fine. However, the float array it returns are 6 zero values truncated to 2 decimal places (I need all 3).

The values are truncated by something else you are doing, not by the fact that you are compounding error on top of error in this function.

Yea I realized my error shortly after I posted heh. Must be this lack of sleep :astonished: