Array Question

I need to create a method (constructor) to initialize a bigint to an int value you provide [0, maxint]. Example: bigint(128).

Here is my class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 #ifndef BIGINT_H
#define BIGINT_H

const int MAXINT = 500;

class bigint{
	public:
		bigint();
		bigint(int);
		bigint(char);
		void output (std::ostream& out);
		bool compare(bigint, bigint);

	private:
		int size[MAXINT];
};

#endif 


So if the user inputs (4123 for example). How would I make 4 in size[0], 1 in size [1], 2 in size [2], etc. I don't even know where to start. Im guessing I would start with a for loop but I need some help.
Last edited on
Since (I'm assuming) the user can input a number with up to 500 digits, you may want to pass a string to your constructor rather than an integer. You could then convert each character in the string to an integer (using the ASCII table) and store them in your array.

Edit: here's a program that illustrates this idea:

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
#include <iostream>

using namespace std;

int char_to_int(char c)
{
    return c - 48;
}

int main()
{
    const int array_size = 500;
    int array[array_size];
    
    string str = "123456789012345678901234567890";
    int str_size = str.length();
    
    for (int i = 0; i < str_size; ++i)
    {
        array[i] = char_to_int(str[i]);
    }
    
    for (int i = 0; i < str_size; ++i)
    {
        cout << array[i];
    }
    
    return 0;
}
Last edited on
I would rather write return c - '0'; on line 7 to make things extra clear.

Also, for an int, you could just use the modulo/divide method:
1
2
3
4
5
6
7
8
int arr[500] = {};
int toconvert(92387);

size_t I(0);
while(toconvert > 0){
   arr[I++] = toconvert%10;
   toconvert /= 10;
}


Just two things with my code snippet:
-You'd have to check if the number is negative before going through the loop.
-The number image would actually be stored in reverse: 78329 (followed by a bunch of 0's). I personally find this easier to work with, but it wouldn't be too difficult to reverse the image to 92387.
Last edited on
I do understand how to do it with a string but we have to do it with an integer for this part. Im not sure how to access single digits of an integer. Can anyone help?
Peruse Daleth's post.
Topic archived. No new replies allowed.