C++ get each digit in int

前端 未结 13 1287
谎友^
谎友^ 2020-12-02 21:50

I have an integer:

int iNums = 12476;

And now I want to get each digit from iNums as integer. Something like:

foreach(iNum          


        
相关标签:
13条回答
  • 2020-12-02 21:58
    int iNums = 12345;
    int iNumsSize = 5;
    for (int i=iNumsSize-1; i>=0; i--) {
        int y = pow(10, i);
        int z = iNums/y;
        int x2 = iNums / (y * 10);
        printf("%d-",z - x2*10 );
    }
    
    0 讨论(0)
  • 2020-12-02 21:58

    To get digit at "pos" position (starting at position 1 as Least Significant Digit (LSD)):

    digit = (int)(number/pow(10,(pos-1))) % 10;
    

    Example: number = 57820 --> pos = 4 --> digit = 7


    To sequentially get digits:

    int num_digits = floor( log10(abs(number?number:1)) + 1 );
    for(; num_digits; num_digits--, number/=10) {
        std::cout << number % 10 << " ";
    }
    

    Example: number = 57820 --> output: 0 2 8 7 5

    0 讨论(0)
  • 2020-12-02 21:59

    I don't test it just write what is in my head. excuse for any syntax error

    Here is online ideone demo

    vector <int> v; 
    
    int i = ....
    while(i != 0 ){
        cout << i%10 << " - "; // reverse order
        v.push_back(i%10); 
        i = i/10;
    }
    
    cout << endl;
    
    for(int i=v.size()-1; i>=0; i--){
       cout << v[i] << " - "; // linear
    }
    
    0 讨论(0)
  • 2020-12-02 22:01

    Convert it to string, then iterate over the characters. For the conversion you may use std::ostringstream, e.g.:

    int iNums = 12476;
    std::ostringstream os;
    
    os << iNums;
    std::string digits = os.str();
    

    Btw the generally used term (for what you call "number") is "digit" - please use it, as it makes the title of your post much more understandable :-)

    0 讨论(0)
  • 2020-12-02 22:02
    void print_each_digit(int x)
    {
        if(x >= 10)
           print_each_digit(x / 10);
    
        int digit = x % 10;
    
        std::cout << digit << '\n';
    }
    
    0 讨论(0)
  • 2020-12-02 22:02

    You can do it with this function:

    void printDigits(int number) {
        if (number < 0) { // Handling negative number
            printf('-');
            number *= -1;
        }
        if (number == 0) { // Handling zero
            printf('0');
        }
        while (number > 0) { // Printing the number
            printf("%d-", number % 10);
            number /= 10;
        }
    }
    
    0 讨论(0)
提交回复
热议问题