如何在C++中将数字拆分为数字

How to split a number into digits in C++

本文关键字:数字 拆分 C++      更新时间:2023-10-16

我知道在 Stack 溢出上也有类似的问题。我已经检查过了。这里有两点:

该数字
  1. 将是用户的输入,因此我不知道该数字实际上可能包含多少位数字

  2. 我不想直接打印数字,我需要对每个数字进行进一步的处理,所以我需要一种方法来保存或分配每个数字。 例如,如果用户输入 1027,我需要返回 1、0、2、7,而不是打印。这就是我的问题开始的地方。 如果可以打印,我会这样写它:

int x;
cin>>x;
while(x != 0)
{
cout<<x%10<<endl;
x/=10;
}

任何提示或帮助都提前表示赞赏。

这取决于您需要它的顺序。如果您需要从最低有效数字(最右边(到最重要(最左边(,那么您的解决方案几乎就在那里

int x = ...
while(x != 0)
{
int current = x % 10; // get rightmost digit
x /= 10;
// process 'current', or store in a container for later processing
}

如果您需要最重要(最左边(到最不重要(最右边(,那么您可以递归执行此操作:

void for_each_digit(int input)
{
// recursive base case
if (input == 0) { return; };    
int current = input % 10
for_each_digit(input / 10); // recurse *first*, then process
// process 'current', add to container, etc
}
// ...

int x = ...
for_each_digit(x);

编辑:我显然错过了关于返回数字序列的部分。

这两种方法都有效。如果从右到左,则需要先反转容器。如果使用递归,则需要将每个值附加到容器中。

使用std::string

std::string input;
std::cin >> input;

现在input[i]是第i位数字。input.size()是位数。

好吧,你可以使用向量。它可以接受可变长度的输入。您无需事先声明尺寸。在此处了解有关矢量的更多信息: 矢量

#include<iostream>
#include<vector>
#include <algorithm> // std::reverse
using namespace std;
int main(void)
{
vector<int>digits;
int x;
cin >> x;
while(x)
{
digits.push_back(x % 10);
x = x / 10;
}
// reversing the order of the elements inside vector "digits" as they are collected from last to first and we want them from first to last.
reverse(digits.begin(), digits.end());

// Now the vector "digits" contains the digits of the given number. You can access the elements of a vector using their indices in the same way you access the elements of an array.
for(int i = 0; i < digits.size(); i++) cout << digits[i] << " ";
return 0;
}

您可以尝试std::vector<int>存储未知数量的整数,如下所示:

#include <iostream>
#include <vector>
int main(void) {
std::vector<int> digits;
std::string s;
std::cout << "Enter the number: ";
std::cin >> s;
size_t len = s.length();
for (size_t i = 0; i < len; i++) {
digits.push_back(s[i] - '0');
}

// Comment next 3 code to stop getting output
for (size_t i = 0; i < len; i++)
std::cout << digits[i] << ' ';
std::cout << std::endl;
return 0;
}

注意:此方法不执行任何数学运算(即除法运算和获取余数(。它只是使用 for 循环将每个整数存储在向量中。