Suppose I have a string "12345" but want to make it into an array, what code or function allows me to do that?
Example:
I input: "12345" and I want it to turn into the array (same as typing) [1, 2, 3, 4, 5] in c++. I know that the function stoi.("12345") converts the string into an integer, but how would I go about making that integer be an array?
You can write such function:
std::vector<int> toIntArray(const std::string& str) {
const std::size_t n = str.length();
std::vector<int> digits(n);
for (std::size_t i = 0; i < n; ++i)
digits[i] = str[i] - '0'; // converting character to digit
return digits;
}
Or if you cannot use std::vector
:
void toIntArray(int* digits, const char* str) {
while (*str) {
*digits++ = *str++ - '0';
}
}
But you have to be confident array size is enough to store all digits.