how do i break an int down to its individual digits?

This is just a small part of a bigger problem i got to solve. suppose I got a int 126.
Because it is a whole number, it cannot be split into bits can it? If i had a string someword;

I could do this to look at the individul letter making the word.:

(for int i=0; int != someword.size; ++i)
{
someword[i];
}

This does not work with a int because it is an int. Is it possible to do this in c++, so that a program can read a given int and separate the digits of it?
You can use some mathematical algorithms or convert your number in a string via stringstreams:
1
2
3
4
5
int n = 126;//Your number
stringstream ss;//a stringstream
ss << n;// add 126 to the stringstream
string result = ss.str(); //set the contents of the stream to a string
//now result == "126" 
Here's a way to do it with math:
1
2
3
4
5
6
7
int getDigit(int digitIndex,int N, int base)
{ if (N<0){N=-N;} 
  for(int i=0;i<digitIndex;i++)
  { N/=base;
  }
  return (N% base);
}
Last edited on
you can simply read an integer using cin ,to split ityse modulus operator
suppose you want the user to enter 4digit number then
int num;
int ones, tens,thou,hun;
cout<<"enter number";
cin>>num;
ones=num%10;
num=num/10;
tens=num%10;
num=num/10;

hun=num%10;
num=num/10;
thou=num%10;
num=num/10;

hope this will help you
Last edited on
Also note that that approach can be generalized to support other bases, as well.
Topic archived. No new replies allowed.