Problem with integer array

I have a little problem with integer and array.
I want to receive a values from user and split it to array in one line.
For example,the value is 7890 (receive it in one line)
and then put it in array like this a[0]=7,a[1]=8,a[2]=9,a[3]=0 .




1 - get the input in a string
2 - create an array in the free store or use a container using the length of that string as size
3 - convert each character of the string in an item for the array
Last edited on
If you want without string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

int main()
{
        int A[10]; // int has 10 digits
        int n, i = 0, j, len, tmp;

        cin >> n;
        n = ( n >= 0 ) ? n : -n;

        do {
                A[i++] = n % 10;
        } while ( (n /= 10) > 0 );

        len = i;
        // reverse
        for ( i = 0, j = len - 1; i < j; ++i, --j )
        {
                tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
        }

        for ( i = 0; i < len; ++i )
        {
                cout << "A[" << i << "] = " << A[i] << endl;
        }

        return 0;
}


ref: http://en.wikipedia.org/wiki/Itoa

But Bazzy way is simpler and faster.
Could you read in a string, use the STL reverse method on the string, and then just use the string to access each digit, performing the conversion from ASCII char to numeric char after retrieval?

Here's what I meant; it will supplement what jsmith and Bazzy contributed:
1
2
3
4
5
6
#include <algorithm>

string number = "7890";
reverse( number.begin(), number.end() );

// number would now be "0987" so that the subscripts would match up as you requested 
Last edited on
1
2
3
4
Bazzy (192) Nov 14, 2008 at 10:27pm 
1 - get the input in a string
2 - create an array in the free store or use a container using the length of that string as size
3 - convert each character of the string in an item for the array 


Thank you but
Could you please show me at step 3 convert each character of the string in an item for the array. Thank a lot.
1
2
char ch = '5';
cout << static_cast<int>( ch - '0' ) << endl;


outputs 5. Note that this works on ASCII systems but may not work on non-ASCII based systems.

To get a character from a string, you can use sub-scripting:
mystring[n] returns the character at positin n in mystring (notice that the first character will have position 0).
1
2
3
4
int number;
cin >> number;
char array[100] = { 0 };
sprintf(array, "%i", number);


It's a very C style'd approach, but it'll do the trick.
Topic archived. No new replies allowed.