I have a std::string: 01001, I want to get each number:
std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = atoi( foo[i] );  // fail
   int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}
How to do that?
This is the easiest way I see:
std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = foo[i] - '0';
}
                        If you know all characters of foo are digits, you can use (int) (foo[i] - '0') which subtracts the ascii value of '0' from the character. This works for all digits because their ascii values are consecutive.
Your first attempt fails because foo[i] is a single char, while atoi() takes a cstring. Your second attempt fails because &foo[i] is a reference to that character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With