49

How can I split an int in c++ to its single numbers? For example, I'd like to split 23 to 2 and 3.

ewggwegw
  • 4,262
  • 5
  • 26
  • 27
  • 9
    Think of it as a brainteaser. If you still can't work out how to do it, post what you tried and people can comment. – Alex Brown Nov 23 '10 at 22:25
  • 2
    possible duplicate of [Split an Integer into its digits c++](http://stackoverflow.com/questions/4207696/split-an-integer-into-its-digits-c) – Steve Townsend Nov 23 '10 at 23:14

17 Answers17

146

Given the number 12345 :

5 is 12345 % 10
4 is 12345 / 10 % 10
3 is 12345 / 100 % 10
2 is 12345 / 1000 % 10
1 is 12345 / 10000 % 10

I won't provide a complete code as this surely looks like homework, but I'm sure you get the pattern.

icecrime
  • 74,451
  • 13
  • 99
  • 111
18

Reversed order digit extractor (eg. for 23 will be 3 and 2):

while (number > 0)
{
    int digit = number%10;
    number /= 10;
    //print digit
}

Normal order digit extractor (eg. for 23 will be 2 and 3):

std::stack<int> sd;

while (number > 0)
{
    int digit = number%10;
    number /= 10;
    sd.push(digit);
}

while (!sd.empty())
{
    int digit = sd.top();
    sd.pop();
    //print digit
}
swaroop
  • 93
  • 1
  • 10
Svisstack
  • 16,203
  • 6
  • 66
  • 100
  • 1
    I remembered what you say, when i was reverse engineering an executable, i see how are stored the characters, like to first value on the high part of memory and the end value was lowest address than the ultimate, i surprised when i see your comment!! – deon cagadoes Dec 14 '19 at 20:21
  • 1
    Actually that should be do-while-loops, otherwise you will not generate the correct result for input 0. – fschmitt Jun 29 '21 at 13:22
3

The following will do the trick

void splitNumber(std::list<int>& digits, int number) {
  if (0 == number) { 
    digits.push_back(0);
  } else {
    while (number != 0) {
      int last = number % 10;
      digits.push_front(last);
      number = (number - last) / 10;
    }
  }
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
2

A simple answer to this question can be:

  1. Read A Number "n" From The User.
  2. Using While Loop Make Sure Its Not Zero.
  3. Take modulus 10 Of The Number "n"..This Will Give You Its Last Digit.
  4. Then Divide The Number "n" By 10..This Removes The Last Digit of Number "n" since in int decimal part is omitted.
  5. Display Out The Number.

I Think It Will Help. I Used Simple Code Like:

#include <iostream>
using namespace std;
int main()
{int n,r;

    cout<<"Enter Your Number:";
    cin>>n;


    while(n!=0)
    {
               r=n%10;
               n=n/10;

               cout<<r;
    }
    cout<<endl;

    system("PAUSE");
    return 0;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

Declare an Array and store Individual digits to the array like this

int num, temp, digits = 0, s, td=1;
int d[10];
cout << "Enter the Number: ";
cin >> num;
temp = num;
do{
    ++digits;
    temp /= 10;
} while (temp);

for (int i = 0; i < digits-1; i++)
{
    td *= 10;
}

s = num;
for (int i = 0; i < digits; i++)
{
    d[i] = s / td %10;
    td /= 10;

}
Gopiraj
  • 647
  • 7
  • 19
1

cast it to a string or char[] and loop on it

Ali Tarhini
  • 5,278
  • 6
  • 41
  • 66
1

the classic trick is to use modulo 10: x%10 gives you the first digit(ie the units digit). For others, you'll need to divide first(as shown by many other posts already)

Here's a little function to get all the digits into a vector(which is what you seem to want to do):

using namespace std;
vector<int> digits(int x){
    vector<int> returnValue;
    while(x>=10){
        returnValue.push_back(x%10);//take digit
        x=x/10; //or x/=10 if you like brevity
    }
    //don't forget the last digit!
    returnValue.push_back(x);
    return returnValue;
}
rtpg
  • 2,419
  • 1
  • 18
  • 31
  • x%10 gives you last digit not first, and you code will return numbers in vector but in reversed order. – Svisstack Nov 23 '10 at 22:46
  • I always saw the units as the first digit. Granted, my code does send the digits in reverse order, but it does avoid having to know the "length" of x mid-function. – rtpg Nov 23 '10 at 22:51
  • using a deque you could push front and have them in the correct order – David Nov 24 '10 at 00:02
1
int n = 1234;
std::string nstr = std::to_string(n);
std::cout << nstr[0]; // nstr[0] -> 1

I think this is the easiest way.

We need to use std::to_string() function to convert our int to string so it will automatically create the array with our digits. We can access them simply using index - nstr[0] will show 1;

0
int n;//say 12345
string s;
scanf("%d",&n);
sprintf(s,"%5d",n);

Now you can access each digit via s[0], s[1], etc

three_pineapples
  • 11,579
  • 5
  • 38
  • 75
0

You can count how many digits you want to print first

#include <iostream>
#include <cmath>
using namespace std;

int main(){
int number, result, counter=0, zeros;

do{
    cout << "Introduce un numero entero: ";
  cin >> number;

  }while (number < 0);

  // We count how many digits we are going print
  for(int i = number; i > 0; i = i/10)
        counter++;

   while(number > 0){

       zeros = pow(10, counter - 1);

       result = number / zeros;
       number = number % zeros;
       counter--;

       //Muestra resultados
       cout << " " << result;
   }
   cout<<endl;

}

Javi
  • 1
0

Based on icecrime's answer I wrote this function

std::vector<int> intToDigits(int num_)
{
    std::vector<int> ret;
    string iStr = to_string(num_);

    for (int i = iStr.size() - 1; i >= 0; --i)
    {
        int units = pow(10, i);
        int digit = num_ / units % 10;
        ret.push_back(digit);
    }   

    return ret;
}
radcore
  • 329
  • 2
  • 10
0

Start with the highest power of ten that fits into an int on your platform (for 32 bit int: 1.000.000.000) and perform an integer division by it. The result is the leftmost digit. Subtract this result multipled with the divisor from the original number, then continue the same game with the next lower power of ten and iterate until you reach 1.

jball
  • 24,791
  • 9
  • 70
  • 92
Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122
0

You can just use a sequence of x/10.0f and std::floor operations to have "math approach". Or you can also use boost::lexical_cast(the_number) to obtain a string and then you can simply do the_string.c_str()[i] to access the individual characters (the "string approach").

rodrigob
  • 2,891
  • 3
  • 30
  • 34
0

I don't necessarily recommend this (it's more efficient to work with the number rather than converting it to a string), but it's easy and it works :)

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

#include <boost/lexical_cast.hpp>

int main()
{
    int n = 23984;
    std::string s = boost::lexical_cast<std::string>(n);
    std::copy(s.begin(), s.end(), std::ostream_iterator<char>(std::cout, "\n"));
    return 0;
}
Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80
0
    int power(int n, int b) {
    int number;
    number = pow(n, b);
    return number;
}


void NumberOfDigits() {
    int n, a;
    printf("Eneter number \n");
    scanf_s("%d", &n);
    int i = 0;
    do{
        i++;
    } while (n / pow(10, i) > 1);
    printf("Number of digits is: \t %d \n", i);

    for (int j = i-1; j >= 0; j--) {
        a = n / power(10, j) % 10;
        printf("%d \n", a);
    }
}

int main(void) {
    NumberOfDigits();
}
0

EASY AND BEST:

while (number > 0)
 { 
  int digit = number%10;
  number /= 10;
  cout<<digit<<endl;
 }
-1
#include <iostream>

using namespace std;

int main()

{


int n1 ;

cout <<"Please enter five digits number: ";
cin >> n1;

    cout << n1 / 10000 % 10 << " ";
    cout << n1 / 1000 % 10 << " ";
    cout << n1 / 100 % 10 << " ";
    cout << n1 / 10 % 10 << " ";
    cout << n1 % 10 << " :)";   

cout << endl;

return 0;
}