or
Jonathan Mee
Given `std::string str`, what's the best way to ensure that the entirity of `str` *is* an integer?

 1. [`std::strtol`](http://en.cppreference.com/w/cpp/string/byte/strtol): The entire string has been consumed if after the following block, `std::distance(c_str, const_cast<const char*>(length)) == std::size(str)`

```
char* length;
const auto c_str = std::data(str)
const int num = std::strtol(c_str, &length, 10);
```

 2. [`std::sscanf`](http://en.cppreference.com/w/cpp/io/c/fscanf): The entire string has been consumed if after the following block, `length == std::size(str)`

```
std::size_t length = {};
int num;

std::sscanf(std::data(str), "%d%zn", &num, &length);
```

 3. [`std::stoi`](http://en.cppreference.com/w/cpp/string/basic_string/stol): The entire string has been consumed if the following block did not throw.

```
std::size_t length;
const auto num = std::stoi(str, &length)

if(length != std::size(str))  
{
    throw invalid_argument("invalid stoi argument");
}
```  

[**Live Example**](https://ideone.com/LO2Qnq)
Top Answer
Jonathan Mee
As of C++17 the official answer is [`std::from_chars`](https://en.cppreference.com/w/cpp/utility/from_chars):

> Unlike other parsing functions in C++ and C libraries, `std::from_chars` is locale-independent, non-allocating, and non-throwing. Only a small subset of parsing policies used by other libraries (such as `std::sscanf`) is provided. This is intended to allow the fastest possible implementation.

Additionally, `std::from_chars`:

 * Supports bases 2 to 36
 * Works with both `std::string`s and `char*`s
 * Does not throw on error

It can be used by doing something like:

    int num;
    const auto finish = &*std::cend(str);
    const auto length = std::from_chars(&*std::cbegin(str), finish, num);

The entire string has been consumed if `length.ptr == finish`.

[**Live Example**](https://ideone.com/uVzE4J)
Consider Entire string When Converting to an int

This is a dedicated room for discussion about this question.

Once logged in you can direct comments to the question poster (or any answer poster) here.