-1

Possible Duplicate:
How to convert a number to string and vice versa in C++

How do I convert a char array to integer/double/long type -atol() functions?

2
  • 1
    Do you mean minus atol functions? Like, without using them? Commented Dec 4, 2011 at 15:42
  • What do you mean as "convert"? Do you want to parse the string number representation stored in the string? Do you want to represent character numeric codes in your integer? Commented Dec 4, 2011 at 15:43

5 Answers 5

10

Either Boost.LexicalCast:

boost::lexical_cast<int>("42");

Or (C++11):

std::stoi("42");

Also, don't use char arrays unless it's interop. Use std::string instead. Also don't ever use ato* functions, even in C, they're broken as designed, as they can't signal errors properly.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for introducing std::stoi at SO. I've not seen this before.
5

Writing such a function yourself is a great exercise:

unsigned parse_int(const char * p)
{
    unsigned result = 0;
    unsigned digit;
    while ((digit = *p++ - '0') < 10)
    {
        result = result * 10 + digit;
    }    
    return result;
}

Of course, you should prefer existent library facilities in real world code.

27 Comments

@AlexTheodoridis: "not portable" isn't the same as "many security flaws". If the function is called with NULL as its argument, it will crash immediately. Is that a security flaw?
@Alex: 1) So? There are many C library functions that invoke undefined behavior when being passed a NULL pointer, for example strlen. I wouldn't call that a security flaw. 2) I am doing unsigned comparison. (digit = *p++ - '0') will produce values bigger than 10 for characters below '0'. 3) Every real world character encoding has consecutive digits, even EBCDIC.
@Alex: When exactly does my function generate "unexpected output"? Please provide an example input string, the expected output, and the actual (erroneous) output.
And here i am, unable to downvote comments... :P @Alex: if you can provide an example of this code doing anything other than it was designed to do, feel free to share. Otherwise, quit going on about "security flaws". The most that's going on here is he's assuming that the user of this function is not a moron, and has passed a non-null pointer to a nul-terminated string. Like, you know, pretty much every function in <string.h> assumes.
@Alex The C++ standard guarantees that digits are consecutive. So no, x - '0' does not depend on the ASCII table, it only depends on the C++ standard, which I think is acceptable. (reference: §2.3p4 "In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.")
|
2

Using C++ Streams

std::string hello("123"); 
std::stringstream str(hello); 
int x;  
str >> x;  
if (!str) 
{      
   // The conversion failed.      
} 

Comments

1
template<class In, class Out>
static Out lexical_cast(const In& inputValue)
        {
    Out result;

    std::stringstream stream(std::stringstream::in | std::stringstream::out);
    stream << inputValue;
    stream >> result;
    if (stream.fail() || !stream.eof()) {
        throw bad_cast("Cast failed");
    }

    return result;
}

using it:

int val = lexical_cast< std::string, int >( "123" );

14 Comments

I can craft an invalid input that'll make this function crash. So I guess your version has a security flaw, just like @FredOverflow's?
@jalf Xmm let's tell me and I will fix it :).
Apparently, there is no bad_cast constructor taking a C string.
sorry bad_cast is an exception from my lib you can't use this code as is. This is an example only. You can throw your exception if you wish.
For example, passing std::string(" 123") to this function will work, but passing std::string("123 ") or std::string(" 123 ") will make it throw. Not really robust, IMHO.
|
0

Do you mean how to convert them to integers? You cannot convert an array of characters into a function on the language level - perhaps you can with some compiler specific inline assembler syntax. For doing a conversion into an integer you can use atoi

int i = atoi("123");`

Or strtol

long l = strtol("123", NULL, 10);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.