user60684 user60684 - 3 years ago 121
C++ Question

Split string into string and int

I am trying to use

sscanf(inputCmd, "%s%d", cmd, value);
to convert the string
inputCmd
into the string
cmd
, and the int
value
in my Arduino sketch. However it isn't working, as apparently the variables are the wrong type (String, instead of char*)

inputCmd is in the format FOO90, and neither the length of the number or the string can be assumed to be constant. What is the best way to separate the 2 parts of
inputCmd
and store them in 2 variables?
cmd
should be FOO, and
value
should be 90.

Thanks.

Answer Source

Besides the problem with String versus char*, the scanf format "%s" reads a space-delimited string. If there's no space between the string and the number you can't use sscanf.

As a possible solution you can attempt to get a substring of each part of the input string, and for the number-part convert it to an int.

To find out the length of the first substring (which should be put into cmd) and the starting position of the number, you need to iterate over the characters of the string until you find a non-alphabetic character.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download