Convert integer to array

Viewed 108230

I would like to convert an integer into an array, so that it looks like the following:

int number = 123456 ;
int array[7] ;

with the result:

array[0] = 1 
array[1] = 2
...
array[6] = 6
13 Answers
#include <cmath>
#include <vector>    

std::vector<int> vec;
for (int i = log10(input); i >= 0; i--)
{
  vec.push_back(input / int(std::pow(10, i)) % 10);
}

Might be a good approach, I think

if this is really homework then show it your teacher - just for fun ;-)

CAUTION! very poor performance, clumsy way to reach the effect you expect and generally don't do this at home(work) ;-)

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

typedef std::vector< int > ints_t;

struct digit2int
{
    int operator()( const char chr ) const
    {
        const int result = chr - '0';
        return result;
    }
};

void foo( const int number, ints_t* result )
{
    std::ostringstream os;
    os << number;
    const std::string& numberStr = os.str();
    std::transform(
        numberStr.begin(),
        numberStr.end(),
        std::back_inserter( *result ),
        digit2int() );
}

int main()
{
    ints_t array;
    foo( 123456, &array );
    std::copy(
        array.begin(),
        array.end(),
        std::ostream_iterator< int >( std::cout, "\n" ) );
}

To convert an integer to array, you can do the steps below:

  • Get the total number of digits in a number to which we want to convert to array.For this purpose, we will use count_digits() function which will return total no of digits after ignoring leading zeros.
digits = count_digits(n);
  • Now we will dynamically allocate memory for our resulting array, just like
int* arr = new int[count_digits(n)]
  • After allocating memory, we will populate the array using the for loop below
int digits = count_digits(num);
for (int i = digits; i > 0; i--){
    arr[i-1] = num % 10;
    num = num / 10;
}

After performing the steps above, we will be able to convert an integer to array. Remember, num is the number that we want to convert into array and digits is the variable which gives us the number of digits in a given number ignoring leading zeros.

Related