Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string part into integer

Tags:

c++

string

int

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?

like image 496
Max Frai Avatar asked Jan 18 '11 19:01

Max Frai


2 Answers

This is the easiest way I see:

std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = foo[i] - '0';
}
like image 125
Benoit Thiery Avatar answered Oct 02 '22 21:10

Benoit Thiery


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.

like image 39
moinudin Avatar answered Oct 02 '22 23:10

moinudin