Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ get each digit in int

Tags:

c++

I have an integer:

int iNums = 12476;

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

foreach(iNum in iNums){
   printf("%i-", iNum);
}

So the output would be: "1-2-4-7-6-". But i actually need each digit as int not as char.

Thanks for help.

like image 843
Ilyssis Avatar asked Jan 06 '11 12:01

Ilyssis


People also ask

How do I determine the number of digits of an integer in C?

The number of digits can be calculated by using log10(num)+1, where log10() is the predefined function in math. h header file.

How do you find the number of digits in an integer?

The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.

How do you store each digit in an array?

Method 1: The simplest way to do is to extract the digits one by one and print it. Extract the last digit of the number N by N%10, and store that digit in an array(say arr[]). Update the value of N by N/10 and repeat the above step till N is not equals to 0.


1 Answers

void print_each_digit(int x)
{
    if(x >= 10)
       print_each_digit(x / 10);

    int digit = x % 10;

    std::cout << digit << '\n';
}
like image 196
Abyx Avatar answered Oct 02 '22 02:10

Abyx