David Zhu David Zhu - 3 years ago 282
C++ Question

How to convert a numerical string into an int array in C++

Suppose I have a string "12345" but want to make it into an array, what code or function allows me to do that?

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download