-2

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?

11
  • That's what you want. What have you tried? Commented Oct 2, 2017 at 23:53
  • 4
    Welcome to stackoverflow.com. Please take some time to read the help pages, especially the sections named "What topics can I ask about here?" and "What types of questions should I avoid asking?". Also please take the tour and read about how to ask good questions. Lastly please learn how to create a Minimal, Complete, and Verifiable Example. Commented Oct 2, 2017 at 23:53
  • Also, to further clarify, do you want the "array" to be an array of characters or of integers? Commented Oct 2, 2017 at 23:54
  • 1
    And as I feel nice, here's a couple of hints: If you have a std::string containing the number, then you can loop over it. The first character will be the '1' (in your example). And you can easily convert a character from a character to its corresponding numeric equivalent of the digit by simply subtracting the character '0'. I.e. '1' - '0' == 1 Commented Oct 2, 2017 at 23:56
  • 1
    Iterating over the digits of an integer is hard. If you have a string then iterating over the "digits" (really characters) of the string is much easier. And as mentioned in my previous comment, you can easily convert a digit in a character to its corresponding "integer" value. Commented Oct 2, 2017 at 23:57

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Or use the built in functions. coliru.stacked-crooked.com/a/e9fdbe001e9d0df4
I can only use <iostream>, <fstream>, and <string>.
Thank you for taking time out of your day to explain this to me. Really appreciate it.
@DavidZhu If you have no more questions, mark my answer as accepted, please.
@boriaz50 there

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.