String object to int?

I have a Wiring String Object instance containing an integer and I need to convert it to an int. I have searched vainly for a clear and concise solution. Thanks for any help.

The class I am using is: http://arduino.cc/en/Reference/StringObject

Use the toCharArray method to convert the string to a NULL-terminated array of chars. Then use the atoi function to convert the array to an integer.

Thanks PaulS, however I get this in Arduino version 21; I looked at the API

http://arduino.cc/en/Reference/StringToCharArray

and the signature shows that toCharArray() requires no args and returns a pointer, but the error message below seems to be saying it should have a args and returns null…? Is the documentation outdated?

#include <WiServer.h>
...
String mystr = "hello";
mystr.toCharArray();

SimpleClient:69: error: no matching function for call to ‘String::toCharArray()’
/Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/cores/arduino/WString.h:80: note: candidates are: void String::toCharArray(char*, unsigned int)

When there is a disagreement between the code and the documentation, the code is ALWAYS right.

The toCharArray() documentation is wrong. Look at the header file or source code for the String object.

The toCharArray() function is actually declared like this:

void String::toCharArray(char *buf, unsigned int bufsize)

You need to supply a buffer of the right size, AND tell the function how big the buffer is.

Hi,

I thought I'd add a useful example to the above to helps someone trying to get this to work:

String fresh_from_serial = "1432";
char this_char[fresh_from_serial.length() + 1];
fresh_from_serial.toCharArray(this_char, (choppd.length() + 1));
int my_integer_data = atoi(this_char);

Thanks, Sam.

Where does the "(choppd.length() + 1)" come from? I use something similar like below using "sizeof(this_char)" instead (which was copied from other's post).

fresh_from_serial = "1432";
char this_char[fresh_from_serial.length() + 1];
fresh_from_serial.toCharArray(this_char, sizeof(this_char));
int my_integer_data = atoi(this_char);