Std :: string part to integer

I have std :: string: 01001I want to get every 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 it?

+5
source share
4 answers

This is the easiest way:

std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = foo[i] - '0';
}
+9
source

If you know that all characters fooare numbers, you can use (int) (foo[i] - '0')that subtracts the ascii value '0'from the character. This works for all digits because their ascii values ​​are sequential.

Your first attempt failed because it foo[i]is one charand atoi()cstring. The second attempt fails because it &foo[i]is a reference to this character.

+6

:

int res = foo[i] - '0';

atoiaccepts a null-terminated string, not a single character. The subtraction approach works because ten decimal places are guaranteed to be consistently in the character set (obviously, if there is a chance that you will have non-digit characters in the string, you will want to do the correct error handling).

+3
source

One simple way, very close to what you have, is to insert a char in a predefined string:

std::string foo = "01001";
char str[] = {" "};
for (int i=0; i < foo.size(); ++i)
{
   str[0] = foo[i];
   int res = atoi( str );
}
0
source

All Articles