Link to home
Start Free TrialLog in
Avatar of navarros
navarros

asked on

convert basic_string to int

How do I convert a basic_string to an int?
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
To elaborate:

'basic_str::c_str()' gives you access to the contents of the string as a NULL-terminated C-style string, so you can use the usual conversion functions like 'strtol()' or 'atoi()'
Avatar of nietod
nietod

>> basic_str::c_str()' gives you access to the
>> contents of the string as a NULL-terminated
>> C-style string,
But this has to be done with great caution.  You should familarize yourself with the limitations of this function if you intend to use it.   The code jkr published is a safe use of the function, but you have to be careful if you use it in other ways.
>>but you have to be careful if you use it in other ways.

Absolutely - altering the contents of the 'const char*' (note the 'const'!) is an absolute no-no, even if a cast operation would allow you to remove the 'const' qualifier...
But also you have to be careful that array the pointer poitns to i not invalidated.  The pointer returned from c_str() points to an array of a (potentially) temporay nature.  The string object may delete ro alter this array whenever a non-cosntant member function of the string is called, this includes the destructor.  So for exanmple the code

string S = "ABC";
const char *Ptr = S.c_str();
S[0] = 'X'; // changes string, invalidates ptr.

cout << Ptr; // Error.  Ptr is invalid.
Well, now we're silghtly OT, so just the way I'd handle the 'potential temporary nature':

string S = "ABC";
const char *Ptr = strdup ( S.c_str());
S[0] = 'X'; // changes string, Ptr remains valid, but needs 'free()'.
I agree its off topic, I just didn't "like" the way you explained c_str() briefly and didn't mention its dangers.  Its too tempting to ose it for toher things and then run into problems.
template<class T, class E>
T StringTo(const basic_string<E>& source)
{
     basic_istringstream<E> iss(source);
     T ret;
     iss >> ret;
     return ret;
};

int main(int, char*[])
{
     int i = StringTo<int>(wstring(L"123"));
     i = StringTo<int>(string("456"));
     return 0;
}
try this
#include <iostream.h>
#include <string.h>

void main()
{
char *str = "1234";
int a1;
a1=atoi(str);
cout<<a1<<endl;
}
navaross, you got several solutions here as comments. Please accept one of them and close this question.