I have a string of single digit numbers String numstring = "123456789" then I want to take a character from that string and convert it into an integer.
I Have tried combinations of .charAt() and .toInt but I cannot seem to hit the correct method. I couldn't find an explanation to such a simple thing from a search on google either.
I'm sure it is simple, can anyone explain a method?
My approach is to avoid Strings, because they cause memory problems and program crashes on MCUs, and use C-strings (zero terminated character arrays) instead.
char numstring[]="12345";
int num = atoi(numstring);
// or for larger numbers (greater than the maximum for int)
long num2 = atol(numstring);
It is very possible that this string of digits will start with a zero. I was avoiding storing the entire number as one number incase the leading zeroes would be affected.
I'm not sure I was clear with my question, I want to extract a single digit number from the String and convert that single digit number into an int.
Then just say "single digit", because a number or C-string is usually composed of more than one digit.
C-strings are great because you can so easily manipulate them, including changing single digits, and unlike Strings, they don't cause memory problems if used correctly.
As for leading zero digits, that does not matter with the function atoi(). It DOES matter in a C/C++ program, because a leading 0 indicates octal representation. 010 octal = decimal 8.
Try this example
void setup() {
Serial.begin(115200);
while (!Serial); //wait for connection
char numstring[] = "12345";
int num = atoi(numstring); //convert number
Serial.print(numstring);
Serial.print(" = ");
Serial.println(num);
numstring[0] = '0'; //replace the digit '1' with '0'
Serial.print(numstring);
Serial.print(" = ");
Serial.println(atoi(numstring));
}
void loop() {}