开发者

separate digits of a long number in c++

I have for example the long number 12345678901 and I want to get separately each 开发者_C百科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?


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


This will give you digits in variable b.

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


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.


long residual= number;
int base= 10;

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜