Friday 4 May 2012

Convert a String to an Integer

I think that a lot of people is looking for a function to convert a string to an integer because the function ATOI works only with char. 

This is the solution for you project with Arduino:
int stringToNumber(String thisString) {
int i, value, length;
length = thisString.length();
char blah[(length+1)];
for(i=0; i<length; i++) {
blah[i] = thisString.charAt(i);
}
blah[i]=0;
value = atoi(blah);
return value;
}

3 comments:

  1. Thanks heaps, I was able to understand everything required by atoi and get my integer from a string.

    ReplyDelete
  2. dude, if this works, you're my freaking hero!

    ReplyDelete
  3. count yourself as a freaking hero...toughest part of the code I couldn't crack. After reading your function, it makes sense how it all comes together, but man oh man....any string I went on to to figure out how to accomplish this wanted to get very adversarial about it (read a book on common types...blah blah.) You're the only one who KNEW what some of us old time programming guys were looking for and put it up there. Thank you very much kind sir!

    ReplyDelete