C++ 如何将 int 拆分为其数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4261589/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:56:51  来源:igfitidea点击:

How do I split an int into its digits?

c++

提问by ewggwegw

How can I split an int in c++ to its single numbers? For example, I'd like to split 23 to 2 and 3.

如何将 c++ 中的 int 拆分为其单个数字?例如,我想将 23 拆分为 2 和 3。

回答by icecrime

Given the number 12345 :

鉴于数字 12345 :

5is 12345 % 10
4is 12345 / 10 % 10
3is 12345 / 100 % 10
2is 12345 / 1000 % 10
1is 12345 / 10000 % 10

512345 % 10
412345 / 10 % 10
312345 / 100 % 10
212345 / 1000 % 10
112345 / 10000 % 10

I won't provide a complete code as this surely looks like homework, but I'm sure you get the pattern.

我不会提供完整的代码,因为这肯定看起来像家庭作业,但我相信你明白了模式。

回答by Svisstack

Reversed order digit extractor (eg. for 23 will be 3 and 2):

逆序数字提取器(例如,23 将是 3 和 2):

while (number > 0)
{
    int digit = number%10;
    number /= 10;
    //print digit
}

Normal order digit extractor (eg. for 23 will be 2 and 3):

正常顺序数字提取器(例如,23 将是 2 和 3):

std::stack<int> sd;

while (number > 0)
{
    int digit = number%10;
    number /= 10;
    sd.push(digit);
}

while (!sd.empty())
{
    int digit = sd.top();
    sd.pop();
    //print digit
}

回答by JaredPar

The following will do the trick

以下将解决问题

void splitNumber(std::list<int>& digits, int number) {
  if (0 == number) { 
    digits.push_back(0);
  } else {
    while (number != 0) {
      int last = number % 10;
      digits.push_front(last);
      number = (number - last) / 10;
    }
  }
}

回答by Jibran Ejaz

A simple answer to this question can be:

这个问题的简单答案可以是:

  1. Read A Number "n" From The User.
  2. Using While Loop Make Sure Its Not Zero.
  3. Take modulus 10 Of The Number "n"..This Will Give You Its Last Digit.
  4. Then Divide The Number "n" By 10..This Removes The Last Digit of Number "n" since in int decimal part is omitted.
  5. Display Out The Number.
  1. 从用户处读取数字“n”。
  2. 使用 While 循环确保它不为零。
  3. 取数字“n”的模数 10..这会给你它的最后一位数字。
  4. 然后将数字“n”除以 10..这将删除数字“n”的最后一位,因为在 int 小数部分被省略。
  5. 显示数字。

I Think It Will Help. I Used Simple Code Like:

我认为它会有所帮助。我使用了简单的代码,如:

#include <iostream>
using namespace std;
int main()
{int n,r;

    cout<<"Enter Your Number:";
    cin>>n;


    while(n!=0)
    {
               r=n%10;
               n=n/10;

               cout<<r;
    }
    cout<<endl;

    system("PAUSE");
    return 0;
}

回答by Gopiraj

Declare an Array and store Individual digits to the array like this

声明一个数组并将单个数字存储到这样的数组中

int num, temp, digits = 0, s, td=1;
int d[10];
cout << "Enter the Number: ";
cin >> num;
temp = num;
do{
    ++digits;
    temp /= 10;
} while (temp);

for (int i = 0; i < digits-1; i++)
{
    td *= 10;
}

s = num;
for (int i = 0; i < digits; i++)
{
    d[i] = s / td %10;
    td /= 10;

}

回答by Maciej Adamski

int n = 1234;
std::string nstr = std::to_string(n);
std::cout << nstr[0]; // nstr[0] -> 1

I think this is the easiest way.

我认为这是最简单的方法。

We need to use std::to_string() function to convert our int to string so it will automatically create the array with our digits. We can access them simply using index - nstr[0] will show 1;

我们需要使用 std::to_string() 函数将我们的 int 转换为字符串,以便它会自动创建包含我们的数字的数组。我们可以简单地使用索引访问它们 - nstr[0] 将显示 1;

回答by Ali Tarhini

cast it to a string or char[] and loop on it

将其转换为字符串或 char[] 并在其上循环

回答by rtpg

the classic trick is to use modulo 10: x%10 gives you the first digit(ie the units digit). For others, you'll need to divide first(as shown by many other posts already)

经典技巧是使用模 10:x%10 为您提供第一个数字(即个位数字)。对于其他人,您需要先划分(如许多其他帖子所示)

Here's a little function to get all the digits into a vector(which is what you seem to want to do):

这是一个将所有数字转换为向量的小函数(这似乎是您想要做的):

using namespace std;
vector<int> digits(int x){
    vector<int> returnValue;
    while(x>=10){
        returnValue.push_back(x%10);//take digit
        x=x/10; //or x/=10 if you like brevity
    }
    //don't forget the last digit!
    returnValue.push_back(x);
    return returnValue;
}

回答by Stuart Golodetz

I don't necessarily recommend this (it's more efficient to work with the number rather than converting it to a string), but it's easy and it works :)

我不一定推荐这个(使用数字比将其转换为字符串更有效),但它很容易并且有效:)

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

#include <boost/lexical_cast.hpp>

int main()
{
    int n = 23984;
    std::string s = boost::lexical_cast<std::string>(n);
    std::copy(s.begin(), s.end(), std::ostream_iterator<char>(std::cout, "\n"));
    return 0;
}

回答by rodrigob

You can just use a sequence of x/10.0f and std::floor operations to have "math approach". Or you can also use boost::lexical_cast(the_number) to obtain a string and then you can simply do the_string.c_str()[i] to access the individual characters (the "string approach").

您可以使用一系列 x/10.0f 和 std::floor 操作来获得“数学方法”。或者您也可以使用 boost::lexical_cast(the_number) 来获取字符串,然后您可以简单地执行 the_string.c_str()[i] 来访问单个字符(“字符串方法”)。