use of atoi

i have a string xxxxxxxxxxxxxxxxxxx

i am reading the string into a structure of smaller strings, and using substr to parse it.
i need to convert one of those string types to integer.

atoi is not working for me,. any ideas? it says cannot convert std::string to const char*

It won't take a string, You need to pass it a C style string.
so, say your string is Numbers you need to pass Numbers.c_str() to atoi

Oh, and just in case you didn't know. The string we use is a container made to hold the text. while the C style string is just a null terminated array of characters.
Last edited on
Your problem is that you use string but the atoi needs const char *.

int atoi ( const char * str );

You should use the c_str function of the string class. I.e:

string str;

int number = atoi(str.c_str());

You should check the conversion!

"Return Value
On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned."


You can read a number directly to an integer variable:

int number;

cin >> number;
So, if my string is 16.

typedef A
string length;

A.length = line.substr(x,y)

const char *ptr;
ptr = A.length.c_str();

uint8 num;
num = atoi(ptr);

ptr works ... it shows value = 16, but num dosent show anything,. so atoi is not working, any guesses?
Have you looked at the value of A.length before passing it to atoi? You'll get zero if the string doesn't start with +/- or a number.
Please read this. Consider some of the other alternatives before using atoi. If you are already using std::string why not use streams to get the job done?
Topic archived. No new replies allowed.