954,487 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Conversion from Char* to int ?

Hi All,

I want to convert char * to int.

Plz help me out.

Thanks in advance.

RohitSahni
Light Poster
35 posts since Jul 2007
Reputation Points: 25
Solved Threads: 0
 

What exactly do you mean?
Do you
a) want to convert an array of ASCII characters into an int:

char *numstr = "1234";
int val = atoi(numstr);    // val now = 1234


b) convert the pointer to an int:

char *xyz;   // given contents somewhere
int addr = (int)xyz;   // addr now = the char pointer
dougy83
Posting Whiz in Training
275 posts since Jun 2007
Reputation Points: 85
Solved Threads: 45
 

Thanks a lot for your Rply..i will be using atoi().
And it worked for me. :)

RohitSahni
Light Poster
35 posts since Jul 2007
Reputation Points: 25
Solved Threads: 0
 

Don't use atoi() - here's how to do it in C++

#include <sstream>
#include <iostream>

int main()
{
    const char* foo("1234");
    std::stringstream ss(foo);
    int i;
    if( ss >> i )
        std::cout << "i is: " << i ;
    else
        std::cout << "error";
}


The reason for using stringstreams is that your conversion will fail if the string contains anything which can't be converted to an int - which, if you're dealing with user input, is a real problem. if you use a stringstream, you can detect the error, without it messing up the rest of the program.

Bench
Posting Pro
577 posts since Feb 2006
Reputation Points: 307
Solved Threads: 63
 
Don't use atoi()


Why?

Hamrick
Posting Whiz
325 posts since Jun 2007
Reputation Points: 180
Solved Threads: 34
 

I suppose I should add that atoi() has no reliable way of handling any errors that might be thrown up when your conversion fails. This is where stringstreams provide a far more robust solution, that you can test for failure before using the retrieved value.

Bench
Posting Pro
577 posts since Feb 2006
Reputation Points: 307
Solved Threads: 63
 
~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You