Convert from char to int using atoi

Hello!

So, i am constructing a class called HugeIntegers. I want to do simple math (add, subtract etc) with number with length of say, 40 (just for educational purposes). In the class I have defined a function to ask the user for a number. This it what it looks like (digits is defined in the header: int digits[40]):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void HugeInteger::input()
{
    char digitsChar[40];
    
    for (size_t i = 0; i < 40; i++)
        digitsChar[i] = ' ';
    
    cout << "Enter huge integer: ";
    cin >> digitsChar;

    // convert from char to int
    for (size_t i = 0; i < 40; i++)
    {
        if (digitsChar[i] != ' ')
            digits[i] = atoi(digitsChar[i]);
    }
}


The problem is that the compiler complaints about line 15. I thought this was a valid way of doing things. Am I wrong?

From g++:
HugeInteger.cpp:27:43: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]


And maybe there is there a more "correct" way of doing this?
The problem is that atoi expects a character array, but you only provide it with a single character.

To give atoi what it wants, drop the [i].

atoi(digitsChar);

Now if you do this, then digits doesn't need to be an array. I'm guessing that you want to store each digit as an element of an array. It's easier then to do it this way:

1
2
if (digitsChar[i] >= '0' && digitsChar[i] <= '9')
    digits[i] = digitsChar[i]-'0';


This line will convert a character to an integer. Now you don't need atoi.
Of course. Stupid me :) Thanks a lot!
Topic archived. No new replies allowed.