Ilyssis
Ilyssis

Reputation: 4949

How to get each digit in an int in order?

I have an integer:

int iNums = 12476;

and I want to get each digit from it as an integer. Something like:

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

So the output would be:

1-2-4-7-6-

But I need each digit as an int not as char.

Upvotes: 27

Views: 155076

Answers (17)

Sanket Pagadpalliwar
Sanket Pagadpalliwar

Reputation: 26

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

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

Upvotes: 0

Muhammad Umer Yasin
Muhammad Umer Yasin

Reputation: 149

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

Upvotes: 0

Israil
Israil

Reputation: 1

int a;
cout << "Enter a number: ";
cin >> a;

while (a > 0) {
    cout << a % 10 << endl;
    a = a / 10;             
}

Upvotes: -1

Sourabh Verma
Sourabh Verma

Reputation: 71

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

Upvotes: 3

Rami Awar
Rami Awar

Reputation: 750

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!

Upvotes: 0

KostasA
KostasA

Reputation: 5570

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

Upvotes: 0

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

Upvotes: 5

Matt
Matt

Reputation: 20776

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.

Upvotes: 0

nrofis
nrofis

Reputation: 9766

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

Upvotes: 2

Snowman Tackler
Snowman Tackler

Reputation: 29

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

Upvotes: 0

Jens Bodal
Jens Bodal

Reputation: 1757

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)

Upvotes: 0

Abyx
Abyx

Reputation: 12918

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

    int digit = x % 10;

    std::cout << digit << '\n';
}

Upvotes: 64

Michael Smith
Michael Smith

Reputation: 411

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

Upvotes: 0

D.Shawley
D.Shawley

Reputation: 59553

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.

Upvotes: 11

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116266

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

Upvotes: 30

user467871
user467871

Reputation:

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
}

Upvotes: 2

Ali El-sayed Ali
Ali El-sayed Ali

Reputation: 451

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

Upvotes: -16

Related Questions