[英]Storing digits in array, C++
I'm taking the digits from a number, how can I store them in an array?我正在从一个数字中获取数字,如何将它们存储在数组中?
int main()
{
int n;
std::cin>>n;
while (n > 0)
{
int digit = n%10;
n /= 10;
std::cout<<digit<<" ";
}
return 0;
}
The best approach is proably to use a vector since they can be easily resized at runtime, something like:最好的方法是使用向量,因为它们可以在运行时轻松调整大小,例如:
int main()
{
int n;
std::cin>>n;
std::vector<int> digitArray;
while (n > 0)
{
int digit = n%10;
n /= 10;
std::cout<<digit<<" ";
digitArray.push_back(digit);
}
std::reverse(digitArray.begin(), digitArray.end()); // reverse the order of digits
return 0;
}
Vectors can be accessed just like C-style arrays: digitArray[0]
= the first digit.可以像 C 风格的数组一样访问向量: digitArray[0]
= 第一个数字。
Another approach to take might be to use a fixed size array since we know that a 32-bit integer can only be up to 10 digits long, something like:另一种方法可能是使用固定大小的数组,因为我们知道 32 位整数最多只能有 10 位长,例如:
int main()
{
int n;
std::cin>>n;
int digitArray[10] = {0}; //initialize all elements to 0
int size = 0;
while (n > 0)
{
int digit = n%10;
n /= 10;
std::cout<<digit<<" ";
digitArray[size] = digit;
++size;
}
std::reverse(std::begin(digitArray), std::begin(digitArray)+(size-1)); // reverse the order of digits
return 0;
}
This will leave you with useless elements most of the time, though that probably won't matter here.大多数时候这会给你留下无用的元素,尽管这在这里可能无关紧要。
First count the number of digits, then create a dynamic array and push the digits from highest to lowest index 0
as you move from lsb to msb:首先计算数字的数量,然后创建一个动态数组并在您从 lsb 移动到 msb 时将数字从最高到最低索引0
推送:
int main()
{
int n, count = 0;
std::cin>>n;
int m = n;
while(n > 0)
{
n /= 10;
++count;
}
int *a = new int[count];
while(m > 0)
{
a[--count] = m % 10;
m /= 10;
}
delete[] a; //don't forget to release the memory.
return 0;
}
To do this in c , you must first allocate an array.要在c 中执行此操作,您必须首先分配一个数组。 For a 32 bit int, this could be a fixed array with 10 digits (+ NUL char), eg对于 32 位 int,这可能是一个具有 10 位数字(+ NUL 字符)的固定数组,例如
int main()
{
int n;
std::cin >> n;
char a[11];
int i = 0;
while (n > 0) {
int digit = n % 10;
a[i] = digit;
++i;
n /= 10;
std::cout << digit << " ";
}
a[i] = '\0'; // final NUL byte
// the digits are now stored in reverse order in `a`
return 0;
}
This approach probably helps you to enter any type of digit into an array.这种方法可能会帮助您将任何类型的数字输入到数组中。 even tou can enter any binary digts in it like 00001111.甚至 tou 也可以在其中输入任何二进制数字,例如 00001111。
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n; //enter size of your number
cin>>n;
string input;
cin>>input; //enter your number
int arr[n];
for( int i=0;i<n;i++)
{
arr[i]=input[i] - '0';
}
for(int i=0;i<n;i++)
{
cout<<arr[i];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.