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.
The number of digits can be calculated by using log10(num)+1, where log10() is the predefined function in math. h header file.
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.
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.
void print_each_digit(int x)
{
if(x >= 10)
print_each_digit(x / 10);
int digit = x % 10;
std::cout << digit << '\n';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With