Dchris
Dchris

Reputation: 3077

separate digits of a long number in c++

I have for example the long number 12345678901 and I want to get separately each digit to use it. I tried really hard but I didn't make it so far? Any ideas?

but I have a problem in all of them when I try those with a number of 11 digits and more (that what I want) my program stops working I'm running my program in visual studio in other case-smaller numbers--is just fine.. any connection with the fact that my number is long?

Upvotes: 0

Views: 4029

Answers (5)

Diego Sevilla
Diego Sevilla

Reputation: 29021

Instead of calculating the digits, you can get what you want by converting it into a string:

// This converts the binary representation of the long into a string.
std::stringstream ss;
ss << long_number;
std::string number_as_string = ss.str();

// Then visit all the characters of the string.
for (std::string::const_iterator it = number_as_string.begin();
     it != number_as_string.end();
     ++it)
{
    std::cout << *it << std::endl;
}

This will print the numbers, say, if you have 12345:

1
2
3
4
5

So you can process each of them accessing the iterator *it as the above code.

Upvotes: 0

MSN
MSN

Reputation: 54634

long residual= number;
int base= 10;

do
{
    long digit= residual%base;
    std::cout << digit << '\n';
    residual/= base;
} while (residual!=0);

Upvotes: 0

DGH
DGH

Reputation: 11549

One way would be to convert the number to a string (not sure what the method is for that but I know such things exist) and then access each character of the string one at a time.

Upvotes: 1

icyrock.com
icyrock.com

Reputation: 28628

This will give you digits in variable b.

long a = 12345678901;
while(a > 0) {
   long b = a % 10;
   a /= 10;
}

Upvotes: 2

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133122

std::vector<int> digits;

while(number > 0)
{
   digits.push_back(number%10); //push the last digit in
   number /= 10; //truncate the digit
}

std::reverse(digits.begin(), digits.end()); // the digits were in reverse order

Upvotes: 3

Related Questions