C++ get each digit in int

前端 未结 13 1293
谎友^
谎友^ 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

    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

提交回复
热议问题