C++获取int中的每个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4615046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ get each digit in int
提问by Ilyssis
I have an integer:
我有一个整数:
int iNums = 12476;
And now I want to get each digit from iNums as integer. Something like:
现在我想从 iNums 中获取每个数字作为整数。就像是:
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.
所以输出将是:“1-2-4-7-6-”。但我实际上需要每个数字作为 int 而不是 char。
Thanks for help.
感谢帮助。
采纳答案by Ali El-sayed Ali
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 );
}
回答by Abyx
void print_each_digit(int x)
{
if(x >= 10)
print_each_digit(x / 10);
int digit = x % 10;
std::cout << digit << '\n';
}
回答by Péter T?r?k
Convert it to string, then iterate over the characters. For the conversion you may use std::ostringstream
, e.g.:
将其转换为字符串,然后遍历字符。对于您可以使用的转换std::ostringstream
,例如:
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 :-)
顺便说一句,通常使用的术语(对于您所说的“数字”)是“数字”-请使用它,因为它使您的帖子标题更易于理解:-)
回答by D.Shawley
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.
由于数字相对较少,递归是有界的。
回答by D.Shawley
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
}
回答by nrofis
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;
}
}
回答by Matt
Based on @Abyx's answer, but uses div
so that only 1 division is done per digit.
基于@Abyx 的回答,但使用时div
每个数字只进行 1 个除法。
#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.
NB 仅适用于非负整数。
回答by Rafael Arturo Rocha Vidaurri
To get digit at "pos" position (starting at position 1 as Least Significant Digit (LSD)):
要在“pos”位置获取数字(从位置 1 开始作为最低有效数字 (LSD)):
digit = (int)(number/pow(10,(pos-1))) % 10;
Example: number = 57820 --> pos = 4 --> digit = 7
示例:数字 = 57820 --> pos = 4 --> 数字 = 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
示例:数字 = 57820 --> 输出:0 2 8 7 5
回答by KostasA
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 << ' ';
}
回答by Rami Awar
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!
希望有人觉得这有帮助!
回答by Michael Smith
Drawn from D.Shawley's answer, can go a bit further to completely answer by outputing the result:
从 D.Shawley 的答案中提取,可以通过输出结果来进一步完全回答:
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;
}