string char to int

how can we convert a string char to an integer???????

suppose string s1 = 23

then cout<< s1+10l;
gives an error........how to do that?
There's basically two methods:
The C method involves a call to atoi(), atol(), atof(), or strtod().
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi.html

The C++ method involves stringstreams and is similar to printing output and taking input.

I will explain the C method, since it's the shortest:
We have an std::string s which contains a decimal representation of an integer number. atoi() takes a 'const char *' and returns an int. To get the pointer, we call to std::string::c_str(). We pass this pointer to atoi(), and store atoi()'s return value into an int.
Done.

EDIT: Oh, right. atoi() returns 0 if the string was parsed as zero, or if the string was invalid.
Last edited on
Topic archived. No new replies allowed.