Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

C++ get each digit in int

Writer Matthew Martinez

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.

17 Answers

void print_each_digit(int x)
{ if(x >= 10) print_each_digit(x / 10); int digit = x % 10; std::cout << digit << '\n';
}
8

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 :-)

6

Here is a more generic though recursive solution that yields a vector of digits:

void collect_digits(std::vector<int>& digits, unsigned long num) { if (num > 9) { collect_digits(digits, num / 10); } digits.push_back(num % 10);
}

Being that there are is a relatively small number of digits, the recursion is neatly bounded.

2

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
}
6

Here is the way to perform this action, but by this you will get in reverse order.

int num;
short temp = 0;
cin>>num;
while(num!=0){ temp = num%10; //here you will get its element one by one but in reverse order //you can perform your action here. num /= 10;
}
1

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; }
}

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

1

Drawn from D.Shawley's answer, can go a bit further to completely answer by outputing the result:

void stream_digits(std::ostream& output, int num, const std::string& delimiter = "")
{ if (num) { stream_digits(output, num/10, delimiter); output << static_cast<char>('0' + (num % 10)) << delimiter; }
}
void splitDigits()
{ int num = 12476; stream_digits(std::cout, num, "-"); std::cout << std::endl;
}

I don't know if this is faster or slower or worthless, but this would be an alternative:

int iNums = 12476;
string numString;
stringstream ss;
ss << iNums;
numString = ss.str();
for (int i = 0; i < numString.length(); i++) { int myInt = static_cast<int>(numString[i] - '0'); // '0' = 48 printf("%i-", myInt);
}

I point this out as iNums alludes to possibly being user input, and if the user input was a string in the first place you wouldn't need to go through the hassle of converting the int to a string.

(to_string could be used in c++11)

I know this is an old post, but all of these answers were unacceptable to me, so I wrote my own!

My purpose was for rendering a number to a screen, hence the function names.

void RenderNumber(int to_print)
{ if (to_print < 0) { RenderMinusSign() RenderNumber(-to_print); } else { int digits = 1; // Assume if 0 is entered we want to print 0 (i.e. minimum of 1 digit) int max = 10; while (to_print >= max) // find how many digits the number is { max *= 10; digits ++; } for (int i = 0; i < digits; i++) // loop through each digit { max /= 10; int num = to_print / max; // isolate first digit to_print -= num * max; // subtract first digit from number RenderDigit(num); } }
}

Based on @Abyx's answer, but uses div so that only 1 division is done per digit.

#include <cstdlib>
#include <iostream>
void print_each_digit(int x)
{ div_t q = div(x, 10); if (q.quot) print_each_digit(q.quot); std::cout << q.rem << '-';
}
int main()
{ print_each_digit(12476); std::cout << std::endl; return 0;
}

Output:

1-2-4-7-6-

N.B. Only works for non-negative ints.

My solution:

void getSumDigits(int n) { std::vector<int> int_to_vec; while(n>0) { int_to_vec.push_back(n%10); n=n/10; } int sum; for(int i=0;i<int_to_vec.size();i++) { sum+=int_to_vec.at(i); } std::cout << sum << ' ';
}

The answer I've used is this simple function:

int getDigit(int n, int position) { return (n%(int)pow(10, position) - (n % (int)pow(10, position-1))) / (int)pow(10, position-1);
}

Hope someone finds this helpful!

You can do it using a while loop and the modulo operators. It just gives the digits in the reveser order.

int main() { int iNums = 12476; int iNum = 0; while(iNums > 0) { iNum = iNums % 10; cout << iNum; iNums = iNums / 10; }
}

// Online C++ compiler to run C++ program online

#include <iostream>
#include <cmath>
int main() { int iNums = 123458;

// int iNumsSize = 5;

int iNumsSize = trunc(log10(iNums)) + 1; // Find length of int value
for (int i=iNumsSize-1; i>=0; i--) { int y = pow(10, i);
// The pow() function returns the result of the first argument raised to
the power of the second argument. int z = iNums/y; int x2 = iNums / (y * 10); printf("%d ",z - x2*10 ); // Print Values
} return 0;
}
int a;
cout << "Enter a number: ";
cin >> a;
while (a > 0) { cout << a % 10 << endl; a = a / 10;
}
1
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 );
}
5

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy