Hello,
I am trying to create a function that will convert a String to an integer using arduino-0019(which doesn't have getChars). I do not want to have to modify the String class library to add it back in as I have a whole team that is using the boards, on multiple platforms, and it would be a maintenance issue. Here is what I have been trying and it kind of works but causes memory corruption and the board locks up before too many calls.
int getInt(String text) {
char* text_cstr = "00";
text.toCharArray(text_cstr, 3);
int x = atoi(text_cstr);
free(text_cstr);
if (x == 0 && text != "0") {
x = -1;
}
return x;
}
Any suggestions would be greatly appreciated. Also I only care about double digit numbers at the moment.
Thanks,
Nick
There are some issues with this code. You are not malloc-ing space, so you can't free it.
The 2nd argument to the toCharArray() function is the number of bytes that can be stored in the array, not including the trailing NULL. You have an array that can hold 2 bytes + a NULL, and you are telling toCharAray() that it can write up to 3 characters into it, along with the trailing NULL.
You could do something like this:
int getInt(String text)
{
char temp[20];
text.toCharArray(temp, 19);
int x = atoi(temp);
if (x == 0 && text != "0")
{
x = -1;
}
return x;
}
Your test for valid numeric data in text is not very good. If text contains "000", the int that is returned will be -1. Hmmm...
thank you! that seems to do the trick. I couldn't find a good example of how to use the toCharArray function anywhere and I had my numbers backwards. I am aware the check after atoi isn't that robust but it's all i need for now.
thanks again.
I use the following to convert Serial text to an integer, and it works!
You can easily modify it to read each byte from a string instead.
int SerialReadInt() {
// The string we read from Serial will be stored here:
char str[32];
str[0] = '\0';
int c=0;
while(1<2) {
// See if we have serial data available:
if (Serial.available() > 0) {
// Yes, we have!
// Store it at next position in string:
str[c] = Serial.read();
// If it is newline or we find a variable separator, then terminate the string
// and leave the otherwise infinite loop:
if (str[c] == '\n' || str[c] == '\0') {
str[c] = '\0';
break;
}
// Ok, we were not at the end of the string, go on with next:
else
c++;
}
// In case there are not serial data available, make a short pause before retrying:
else
delayMicroseconds(SERIALREADWAIT);
}
// Convert the string to int and return:
return(atoi(str));
}