How do I split an int into its digits?

前端 未结 15 1498
渐次进展
渐次进展 2020-11-27 17:51

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

相关标签:
15条回答
  • 2020-11-27 18:12
    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

    0 讨论(0)
  • 2020-11-27 18:14

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 18:17

    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;
    }
    
    0 讨论(0)
提交回复
热议问题