Number into array as a single digits

Hi
Let's say I have 4 digit number and I want to extract each digit and assign to array elements. So instead of having int rrrr = 1998 I have a int rrrr[3]={1, 9, 9, 8}.
Is there any simple way of doing this?
hint :
1998 % 10 == 8
1998 % 100 == 98
1998 % 1000 == 998
If you are using C++, you could put it into a stringstream, then read out each character individually and turn it into a integer. Otherwise, you would have to use the '%' and '/' operators to get each part.
I was thinking to use a mod operator also. something like
1998%10 = array[0]
199%10 = array[1]
19%10 = array[2]
1%10 = array[3]

I have the same question but I need the actual code. How do you write the code if you want the user to enter in the values of the array?

These are my thoughts so far (just to show you that I tried :) )

int main() {
int integer, extract[100];
cout << endl << "Enter an integer. I will extract the digits backwards. ";
cin >> integer;

if (integer < 10) extract[0] = integer;
while ( integer >=10) {
for(int i=0; i<=100; i++){ // loops length of array
extract[i]=integer%10;
integer/10;
}
}


Please help !!
Please help !!


for starters what does the "int" in "int main()" do?

secondly lets say this statement is true:
 
1998 % 1000 = 998;
, how do we easily get the first '9' ?
The modulus operator "%" gets remainders of ints.

another question, what happens when you divide an int?
Last edited on
Here is an algorithm. Every line of the algorithm should translate to exactly 1 line of C++ code.


0. Make an array of at least 10 ints (32-bit int has at most 10 digits)
1. Make a counter of the number of used elements in the array.
2. Prompt user to enter a number
3. Read in the number into a variable named "num"
4. Repeat the following steps until there are no more digits in num:
a. Get the ones digit from num into a temporary variable
b. Store the temporary value into the first unused element in the array
c. Increment the number of used elements in the array
d. Modify num so that it contains all but the ones digit.


Topic archived. No new replies allowed.