Getting each individual digit from a whole integer

后端 未结 9 1217
南方客
南方客 2020-11-30 04:05

Let\'s say I have an integer called \'score\', that looks like this:

int score = 1529587;

Now what I want to do is get each digit 1, 5, 2,

9条回答
  •  [愿得一人]
    2020-11-30 04:38

    Agree with previous answers.

    A little correction: There's a better way to print the decimal digits from left to right, without allocating extra buffer. In addition you may want to display a zero characeter if the score is 0 (the loop suggested in the previous answers won't print anythng).

    This demands an additional pass:

    int div;
    for (div = 1; div <= score; div *= 10)
        ;
    
    do
    {
        div /= 10;
        printf("%d\n", score / div);
        score %= div;
    } while (score);
    

提交回复
热议问题