Reputation: 259
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;
}
Upvotes: 0
Views: 12292
Reputation: 1
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.
#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];
}
}
Upvotes: 0
Reputation: 2120
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.
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:
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.
Upvotes: 6
Reputation: 74028
To do this in c, you must first allocate an array. For a 32 bit int, this could be a fixed array with 10 digits (+ NUL char), e.g.
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;
}
Upvotes: 0
Reputation: 13934
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:
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;
}
Upvotes: 0