如何在C++中将数字拆分为数字
How to split a number into digits in C++
我知道在 Stack 溢出上也有类似的问题。我已经检查过了。这里有两点:
该数字将是用户的输入,因此我不知道该数字实际上可能包含多少位数字
我不想直接打印数字,我需要对每个数字进行进一步的处理,所以我需要一种方法来保存或分配每个数字。 例如,如果用户输入 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 循环将每个整数存储在向量中。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 如何在C++中将数字拆分为数字
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 将向量整数拆分为这些数字的整数
- 基于其中的数字子字符串拆分字符串
- 如何在C++中将数字字符串拆分为数组
- 将目标数字拆分为一系列数字(递归任务)
- 正则表达式使用数字作为标记拆分单词
- 如何正确地在字符串中拆分数字
- 如何将数字拆分为其数字并将它们相加,如果存在任何字符,则应"invalid input"输出?
- 将字符数组拆分为字母数字字符和非字母数字字符
- 在c++ /Qt中拆分Lua函数调用的混合字符串/数字参数列表
- 将整数不向后拆分为数字
- 将整数的数字拆分为向量,旋转它们,然后转换回整数
- 如何拆分包含字符和数字的字符串值
- 将项添加到文件内已排序的数字列表中,而不拆分它