I have a string variable of all digits that I am parsing into an array called hugeInt. Doing this in a loop where I pick off one digit at a time out of the string and trying to put into the array. I have tried the code below which uses std::stoi directly and it gives me an error I think because it is a string. So I also tried converting the digit using const char *digit = strInt[j].c_str()
but this gives me an error also. So how do I get what I thought was a one character string (which is a digit) from a real string to convert to an int. code below. My .h file
// HugeInteger.h
#ifndef HUGEINTEGER_H
#define HUGEINTEGER_H
#include <array>
class HugeInteger {
private:
static const int SIZE = 40;
std::array<short int,SIZE> hugeInt;
public:
HugeInteger(long = 0);
HugeInteger(std::string strInt);
void displayHugeInt();
};
#endif
my implementation code
// HugeInteger.cpp
#include <iostream>
#include <stdexcept>
#include "HugeInteger.h"
HugeInteger::HugeInteger(long int num) {
for (short &element : hugeInt) {
element = 0;
}
for (int i = SIZE-1; i >= 0; i--) {
hugeInt[i] = num % 10;
num /= 10;
if (num == 0) {
break;
}
}
}
HugeInteger::HugeInteger(std::string strInt) {
for (short &element : hugeInt) {
element = 0;
}
if (strInt.length() > 40) {
throw std::invalid_argument("String integer is over 40 digits - too large.");
}
for (int i = SIZE-1, j = strInt.length()-1; j >= 0; i--, j--) {
if (isdigit(strInt[j])) {
hugeInt[i] = std::stoi(strInt[j]);
}
else {
throw std::invalid_argument("String integer has non digit characters.");
}
}
}
void HugeInteger::displayHugeInt() {
bool displayStarted = false;
for (short &element : hugeInt) {
if (!displayStarted) {
if (element == 0) {
continue;
}
else {
std::cout << element;
displayStarted = true;
}
}
else {
std::cout << element;
}
}
std::cout << std::endl;
}
The problem is in the second constructor (for a string) in the for loop where hugeInt[i] = std::stoi(strInt[j]);
is. Any help or suggestions welcomed and appreciated.