Re: How to string to int ?
If you attempt to use atoi on a non-integer string (meaning, on the string "Hello", for example), atoi will NOT convert the individual letters to their ASCII equivalents. It will, however, partially convert a string that starts with an integer and has non-integer characters mixed in. For example:
This code results in the output:
The reason for this is that atoi checks the first character for a 0-9 integer value and if found, converts it to an integer. When it comes across a non-integer character it stops converting the characters over.
In the case of Test 1, the decimal '.
' is the non-integer value that stops atoi, so only the integers before it (reading left to right) are converted. Test 2 starts with a non-integer character so no characters are converted nor assigned to Test2. Test 3 stops converting when it reaches the 'H
' character in "Hello".
Note that Test 1 can be fully converted with all of the values intact if using the atof (ASCII to float) function instead:
Because the float data type is only reliable for up to ~7 decimal digits, ROBOTC is able to correctly convert the first four decimal digits (1, 2, 3, and 4), the decimal point, and the next four decimal digits (5, 6, 7, and
. Anything beyond that may or may not calculate correctly, so please be aware of these limitations.
Last but certainly not least, you can also use atoi/atof with character arrays:
Which will return:
Again, unless you specify the amount of decimal places to display in the writeDebugStreamLine, ROBOTC will display the highest resolution it can for the float (8 decimal digits).
We have a full listing of all of the Math commands on our Wiki
that you may want to take a look at as well.
Check out our Blog
! And our Facebook page
Need help? Take a look at our updated help documentation
and the ROBOTC Forums.