title: Safely convert std::string_view to int (like stoi or atoi)
body: <p>Is there a <em>safe standard</em> way to convert <code>std::string_view</code> to <code>int</code>?</p>
  
  <hr>
  
  <p>Since C++11 <code>std::string</code> lets us use <code>stoi</code> to convert to <code>int</code>:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>  std::string str = "12345";
    int i1 = stoi(str);              // Works, have i1 = 12345
    int i2 = stoi(str.substr(1,2));  // Works, have i2 = 23
  
    try {
      int i3 = stoi(std::string("abc"));
    } 
    catch(const std::exception&amp; e) {
      std::cout &lt;&lt; e.what() &lt;&lt; std::endl;  // Correctly throws 'invalid stoi argument'
    }
  </code></pre>
  
  <p>But <code>stoi</code> does not support <code>std::string_view</code>. So alternatively, we could use <code>atoi</code>, but one has to be very careful, e.g.:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>  std::string_view sv = "12345";
    int i1 = atoi(sv.data());              // Works, have i1 = 12345
    int i2 = atoi(sv.substr(1,2).data());  // Works, but wrong, have i2 = 2345, not 23
  </code></pre>
  
  <p>So <code>atoi</code> does not work either, since it is based off the null-terminator <code>'\0'</code> (and e.g. <code>sv.substr</code> cannot simply insert/add one).</p>
  
  <p>Now, since C++17 there is also <code>from_chars</code>, but it does not seem to throw when providing poor inputs:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>  try {
      int i3;
      std::string_view sv = "abc";
      std::from_chars(sv.data(), sv.data() + sv.size(), i3);
    }
    catch (const std::exception&amp; e) {
      std::cout &lt;&lt; e.what() &lt;&lt; std::endl;  // Does not get called
    }
  </code></pre>