例如,我有长号码 12345678901,我想分别获取每个数字以使用它。我真的很努力,但我没有做到这一点?有任何想法吗?
但是当我尝试使用 11 位数及更多位数(我想要的)我的程序停止工作我在 Visual Studio 中以其他情况运行我的程序时 - 较小的数字 - 只是好的..与我的号码很长这一事实有什么联系吗?
例如,我有长号码 12345678901,我想分别获取每个数字以使用它。我真的很努力,但我没有做到这一点?有任何想法吗?
但是当我尝试使用 11 位数及更多位数(我想要的)我的程序停止工作我在 Visual Studio 中以其他情况运行我的程序时 - 较小的数字 - 只是好的..与我的号码很长这一事实有什么联系吗?
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
这将为您提供变量中的数字b
。
long a = 12345678901;
while(a > 0) {
long b = a % 10;
a /= 10;
}
一种方法是将数字转换为字符串(不确定该方法是什么,但我知道存在这样的东西),然后一次访问字符串的每个字符。
long residual= number;
int base= 10;
do
{
long digit= residual%base;
std::cout << digit << '\n';
residual/= base;
} while (residual!=0);
您可以通过将其转换为字符串来获得所需的内容,而不是计算数字:
// 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;
}
这将打印数字,例如,如果您有 12345:
1
2
3
4
5
*it
因此,您可以像上面的代码一样处理它们中的每一个访问迭代器。