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
into the string
, and the int
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
and store them in 2 variables?
should be FOO, and
should be 90.


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