Reputation: 623
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;
}
Upvotes: 3
Views: 18864
Reputation: 61970
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)
std::string s = "1357924680";
std::vector<int> ints;
ints.reserve(s.size()); //to save on memory reallocations, thanks Nawaz
std::transform(std::begin(s), std::end(s), std::back_inserter(ints),
[](char c) {
return c - '0';
}
);
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::vector
instead 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 isdigit
to 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 your ints
vector will be from 0 to 9 and you won't end up with a digit of, say, 25.
Upvotes: 9
Reputation: 19104
You do not need atoi(). Use intNumber[i] = stringNumber[i] - '0';
Upvotes: 6