Problem with toInt() function


#1

I’m using a Particle function and Postman to enable/disable one of several motion sensors. The “args” parameter looks like this:

<enable|disable><zone #>

I’m using the indexOf() function to find the colon and then use toInt() to convert the zone number into an integer. All of this works great, but the issue I’m having is with the return value of toInt().

From the Particle documentation:

“Returns: long (If no valid conversion could be performed because the string doesn’t start with a integral number, a zero is returned.)”

If the function returns a 0 if the string doesn’t start with an integral number, and 0 is a valid integral number, how can the function differentiate between a valid 0 and the letter ‘A’? It seems the return value should be something like -1 to indicate an invalid integer instead of 0, since 0 is a valid integer.

Am I missing something obvious?


#2

That’s a known limitation and has been filed as an issue with Particle and Arduino
https://github.com/particle-iot/device-os/issues/1481

For the time being you’d need to either check the reason for getting a zero or declare a zone 0 as disallowed.
Another option (which I usually use) is to stay clear of String and rather use standard C/C++ functions.

BTW, flipping your order to <zone #><enable|disable> (and possibly even replacing enable and disable with numeric 1 & 0) and introducing a separater would make things somewhat easier.
sscanf() would be a function to consider.


#3

Thanks for the reference @ScruffR.

I had already added code to ignore zone 0, but thanks for the suggestion. I am currently using “:” as a separator between cmd and zone #. I should have put that in the original description.

The only reason for getting a zero in the zone field is that the user incorrectly inputs it into Postman. I was just trying to do some input verification before enabling/disabling a motion sensor.

I guess I should rewrite using char’s and atoi() instead.


#4

Well, i rewrote the whole routine using C character functions, so at least that potential problem is gone. Unfortunately, the C atoi() function suffers from the same issue. I am already ignoring 0 as a valid zone number, so I guess that’s the best I can do for now.


#5

If you use sscanf() you can check the number of successfully parsed items.