How can I split an int in c++ to its single numbers? For example, I\'d like to split 23 to 2 and 3.
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
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;
}
A simple answer to this question can be:
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;
}