Use strtok
to split the char array into the different parts, then use atoi
on each of the parts to convert it to an int. (atoi
ignores whitespace)
char* str = "4532, 4488, 548, 1694, 574";
const size_t bufferSize = 5;
int arr[bufferSize];
char *p = strtok(str, ",");
size_t index = 0;
while (p != nullptr && index < bufferSize) {
arr[index++] = atoi(p);
p = strtok(NULL, ",");
}
for (size_t i = 0; i < index; i++)
Serial.println(arr[i]);
Edit: You just edited your post, and it seems like you really need to use Strings (capital S).
There are two ways to go about it: you have to keep in mind that String::c_str()
returns the actual pointer to the internal null terminated char array inside the String object, and that strtok
is destructive (it replaces the delimiters with null characters).
If you need the String for other things after converting it to an array of ints, you'll have to make a copy first:
String cod = "4532, 4488, 548, 1694, 574";
char *str = new char[cod.length() + 1];
strcpy(str, cod.c_str());
Don't forget to free the memory afterwards:
delete[] str;
If you don't care about destroying the String, you can just use:
String cod = "4532, 4488, 548, 1694, 574";
char *str = cod.c_str();
Edit 2: The ESP8266 compiler doesn't allow implicit conversion from const char*
(read only) to char*
(as strtok
argument). To get around it, the clean solution is to copy it, as explained in my first edit.
If you really don't need the String afterwards, and you don't want to waste memory on the copy, you can just use an explicit type cast:
String cod = "4532, 4488, 548, 1694, 574";
char *str = (char*)cod.c_str();
The AVR compiler doesn't have any problems converting String::c_str()
to char*