title: Is std::stoi actually safe to use?
body: <p>I had a lovely conversation with someone about the downfalls of <code>std::stoi</code>. To put it bluntly, it uses <code>std::strtol</code> internally, and throws if that reports an error. According to them, though, <code>std::strtol</code> shouldn't report an error for an input of <code>"abcxyz"</code>, causing <code>stoi</code> not to throw <code>std::invalid_argument</code>.</p>
  
  <p>First of all, here are two programs tested on GCC about the behaviours of these cases:<br>
  <a href="http://ideone.com/6J6D7" rel="noreferrer">strtol</a><br>
  <a href="http://ideone.com/dHBcd" rel="noreferrer">stoi</a></p>
  
  <p>Both of them show success on <code>"123"</code> and failure on <code>"abc"</code>. </p>
  
  <hr>
  
  <p>I looked in the standard to pull more info:</p>
  
  <p><strong>§ 21.5</strong></p>
  
  <pre class="lang-none prettyprint-override"><code>Throws: invalid_argument if strtol, strtoul, strtoll, or strtoull reports that  
  no conversion could be performed. Throws out_of_range if the converted value is  
  outside the range of representable values for the return type.
  </code></pre>
  
  <p>That sums up the behaviour of relying on <code>strtol</code>. Now what about <code>strtol</code>? I found this in the C11 draft:</p>
  
  <p><strong>§7.22.1.4</strong>  </p>
  
  <pre class="lang-none prettyprint-override"><code>If the subject sequence is empty or does not have the expected form, no  
  conversion is performed; the value of nptr is stored in the object  
  pointed to by endptr, provided that endptr is not a null pointer.
  </code></pre>
  
  <p>Given the situation of passing in <code>"abc"</code>, the C standard dictates that <code>nptr</code>, which points to the beginning of the string, would be stored in <code>endptr</code>, the pointer passed in. This seems consistent with the test. Also, 0 should be returned, as stated by this:</p>
  
  <p><strong>§7.22.1.4</strong>  </p>
  
  <pre class="lang-none prettyprint-override"><code>If no conversion could be performed, zero is returned.
  </code></pre>
  
  <p>The previous reference said that no conversion would be performed, so it must return 0. These conditions now comply with the C++11 standard for <code>stoi</code> throwing <code>std::invalid_argument</code>.</p>
  
  <hr>
  
  <p>The result of this matters to me because I don't want to go around recommending <code>stoi</code> as a better alternative to other methods of string to int conversion, or using it myself as if it worked the way you'd expect, if it doesn't catch text as an invalid conversion.</p>
  
  <p>So after all of this, did I go wrong somewhere? It seems to me that I have good proof of this exception being thrown. Is my proof valid, or is <code>std::stoi</code> not guaranteed to throw that exception when given <code>"abc"</code>?</p>