Convert int to an int array C++

Viewed 248

Given an input from the user (ex. 123456) you must convert the input int to an int array (ex. {1, 2, 3, 4, 5, 6}.

I was wondering, how can this be done? I have started out with a function that counts the digits the were inputted, and initializes an array with the amount of digits.

Is there another way to go about doing this that is simpler?

This is what I have so far:

#include <iostream>
using namespace std;

int main()
{
    int n, counter = 0;
    cin >> n;
    
    while (n != 1)
    {
        n = n / 10;
        counter++;
    }
    counter += 1;
    
    int arr[counter];
    
    return 0;
}
4 Answers

Let me solve this in what is a bit overkill for the problem, but will actually teach you various C++ constructs instead of the "C plus a bit syntactic sugar" you are doing right now.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main( int argc, char * argv[] )
{
    if ( argc != 2 )
    {
        std::cout << "Enter *one* number.\n";
        return 1;
    }

    // Don't work with C arrays any more than you absolutely must.
    // Initializing a variable with those curly braces is the
    // modern C++ way of initialization. The older way using ()
    // had some issues (like the "most vexing parse" problem).
    std::string input { argv[1] };

    // Initialize a vector of int with the elements of input.
    // If you need the elements in reverse order, just use
    // std::rbegin and std::rend.
    std::vector<int> output { std::begin( input ), std::end( input ) };

    // The elements of output right now have a value depending on
    // the character encoding, i.e. they refer to the *character
    // value* of the digit, not the *integer* value. You could
    // call `std::stoi` on each, or you can substract the encoded
    // value for the letter '0', because the standard guarantees
    // that '0' through '9' are encoded with consecutive values.
    // This is NOT true for letters!
    // The part starting at [] is called a "lambda", and it is a
    // very nifty feature in conjunction with <algorithm> that you
    // should study at some point (right after you learned what a
    // 'functor' is, which is probably a bit down the road yet).
    // Think of it as a way to define a local function without
    // giving it a name.
    std::for_each( output.begin(), output.end(), [](int & i){ i -= '0'; } );

    // Prefer range-for over indexed for.
    for ( auto & i : output )
    {
        std::cout << i << "\n";
    }

    return 0;
}

That solution is a bit heavy on the advanced C++ features, though.

This second one is simpler (no <algorithm> or lambdas), but shows proper input error handling and still avoids manual arithmetics on the number:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    int input;

    while ( ! ( std::cin >> input ) )
    {
        // Input can fail, e.g. when the user enters
        // letters.
        std::cout << "Enter a number.\n";
        // Clear the error flag on the input stream.
        std::cin.clear();
        // Clear input buffer of what the user entered.
        std::cin.ignore();
    }

    std::string number { std::to_string( input ) };

    // You *can* reserve space in the vector beforehand,
    // but unless you know you will be pushing a LOT of
    // values, I would not bother. (Also, there are a
    // couple of mistakes you could make if you try.)
    std::vector<int> output;

    for ( auto & c : number )
    {
        output.push_back( c - '0' );
    }

    for ( auto & i : output )
    {
        std::cout << i << "\n";
    }
}

First, the loop you have to calculate how many digits there are in the number only works if the left-most digit is a 1:

while (n != 1)  // what if it's 2-9 instead? 
{
    n = n / 10;
    counter++;
}
counter += 1;

The proper calculation would be

do {
    n /= 10;   // same as n = n / 10
    ++counter;
} while(n);

you must convert the input int to an int array

This requirement is pretty hard to fullfil using standard C++ since the sizes of arrays must be known at compile-time. Some compilers support Variable Length Arrays but using them makes your program non-portable. The tool for creating array-like containers with sizes only known at run-time is the class template std::vector. In this case you want to use a std::vector<int>. I've put the digit-counting part in a separate function here:

#include <iostream>
#include <vector>

int count_digits(int number) {
    int counter = 0;
    do {
        number /= 10;
        ++counter;
    } while (number);
    return counter;
}

int main() {
    int n;
    if (!(std::cin >> n)) return EXIT_FAILURE;

    // instead of  int arr[ count_digits(n) ];  use a vector<int>:
    std::vector<int> arr( count_digits(n) ); 

    // fill the vector starting from the end:
    for(size_t idx = arr.size(); idx--;) {
        arr[idx] = n % 10; // extract the least significant digit
        n /= 10;
    }

    // print the result using an old-school loop:
    for(size_t idx = 0; idx < arr.size(); ++idx) {
        std::cout << arr[idx] << '\n';
    }

    // print the result using a range based for-loop:
    for(int value : arr) {
        std::cout << value << '\n';
    }
}

Alternatively, use a reverse iterator to fill the vector:

    for(auto it = arr.rbegin(); it != arr.rend(); ++it) {
        *it = n % 10;
        n /= 10;
    }

You could also use the standard function std::to_string to convert the int to a std::string (or read the value from the user as a std::string directly).

Once you have a std::string you can easily populate the vector<int> by transformation.

Example:

#include <algorithm>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>

int main() {
    int n;
    if (!(std::cin >> n)) return EXIT_FAILURE;

    auto as_str = std::to_string(n);

    std::vector<int> arr(as_str.size()); // create it big enough to hold all digits

    // transform each character in the string and put the result in arr:
    std::ranges::transform(as_str, arr.begin(), [](char ch) { return ch - '0'; });

    // print the result:
    for (int x : arr) std::cout << x << '\n';
}

The easiest way for you would be to use the same loop that counts the number of digits to save it(using n%10 would give you the last digit in your number). Also you shouldn't use int arr[counter];, since variable length arrays are not supported in c++ even though the code is actually compiled. You should use an array allocated in the heap using int* arr = new int[counter];

The is the simplest way I guess!

int integer_length(int number){
    return trunc(log10(number)) + 1; 
}
Related