5
Contributors
6
Replies
10
Views
9 Years
Discussion Span
Last Post by ~s.o.s~
Featured Replies
  • 1

    Don't use atoi() - here's how to do it in C++ [CODE=CPP]#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"; } [/CODE]The reason for using stringstreams is that … Read More

  • 1
    ~s.o.s~ 2,560   9 Years Ago

    > Why? [URL="http://www.daniweb.com/forums/post191618-8.html"]Answer.[/URL] Read More

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
1

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.

Comments
great post
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.