I am a beginner in C++ and cannot figure this out. Simply as the question says, if I have a string (of a number), how can I convert each digit to an integer and put each into an array of integers?
Here was my attempt:
std::string stringNumber = "123456789"; // this number will be very large
int intNumber[stringNumber.length()];
for (int i = 0; i < stringNumber.length(); i++)
{
intNumber[i] = std::atoi(stringNumber[i]);
std::cout << intNumber[i] << std::endl;
}
For a mostly prebuilt solution, I would use a vector and
std::transform. The idea is to go through each character and add the integer form of it to the vector: (see full sample)What this does is loop through from the beginning of the string to the end, take each character, and add the value of it minus
'0'('5' - '0'would be 5) to the end of the vector, leaving you with a vector of the integer equivalents. Best of all, it doesn’t reinvent the wheel!It also solves two problems you have:
It uses
std::vectorinstead of a variable-length array (VLA). The latter is nonstandard, so prefer a vector if you need a runtime-sized array.You use
atoi, which is bad in itself because it returns 0 on errors, leaving no certainty of whether the result was 0 or whether there was an error. It also takes a string, not a single character. Instead this finds the distance between'0'and the character, which is the integer we need.For an additional layer of security, you can use
isdigitto check whether the character is a digit. If not, raise an error of some sort (like an exception), or deal with it however else you would. This ensures the digits in yourintsvector will be from 0 to 9 and you won’t end up with a digit of, say, 25.