9 years, 10 months ago.

Split string into variables!

I have this string from my sensor

accelx,accely,accelz,gyrox,gyroy,gyroz,magx,magy,magz (with numbers delimited with ',')

i want to divide this string into 9 variables? so then i can use them later.

Any ideas , examples, programs?

2 Answers

9 years, 10 months ago.

I agree with Greg, sscanf can do this. Just for the variety -

http:www.cplusplus.com/reference/cstring/strtok/

strtok() splits a string into tokens, separated by a delimiter. Each becomes an individually accessible string, and then you could use atof() [ascii to float].

I'd give the advantage to the sscanf, which also returns the number of items converted, so this simplifies your processing. On the other hand, I would guess that the strtok/atof have a lower memory footprint (I did not verify this).

There are also C++ solutions - I'll let others provide those.

It's worth noting that strtok is not thread safe.

posted by Stephen Paulger 14 Jul 2014