c++c++11c++14

Converting a character range to int


Suppose we have a character range:

// For example
const char *valueBegin="123blahblah"; // Beginning of value
const char *valueEnd=valueBegin+3;    // One past end of value

..., and I want to convert it to an int:

int value=...// Given valueBegin and valueEnd, calculate 
             // the number stored starting at valueBegin

What are some good C++11 ways to do that?

Obviously you can create an std::string and use stoi, or copy it to a temporary NUL-terminated character array and then it's easy (e.g., via atoi or strtol).

Think about a way that doesn't involve copying the characters to some temporary array/object - in other words a function that works on the character data in-place.

Update:

Lots of answers, but please think before you answer. The range is not NUL terminated, hence the need for valueEnd . You don't know what is beyond the value (i.e., perhaps valueEnd is beyond the buffer containing the value), so if your answer does not use valueEnd, it is wrong. Also, if your answer creates a temporary std::string object, it is not within the guidelines of this question.


Solution

  • Use boost::lexical_cast:

    std::cout << boost::lexical_cast<int>(sBegin, 3) << std::endl;
    

    This does not create any temporaries and supports any kind of character range. It's also quite fast.

    If you want to avoid the length specifier then you can use boost::iterator_range:

    std::cout << boost::lexical_cast<int>(boost::make_iterator_range(begin, end)) << std::endl;