title: How do you get an unsigned long out of a string?
body: <p>What's the safest and best way to retrieve an unsigned long from a string in C++?</p>
  
  <p>I know of a number of possible methods.</p>
  
  <p>First, converting a signed long taken from atol.</p>
  
  <pre><code>char *myStr; // Initalized to some value somehow.
  unsigned long n = ((unsigned)atol(myStr));
  </code></pre>
  
  <p>The obvious problem with this is, what happens when the value stored in myStr is larger than a signed long can contain?  What does atol retrieve?</p>
  
  <p>The next possibility is to use strtoul.</p>
  
  <pre><code>char *myStr; // Initalized to some value somehow.
  unsigned long n = strtoul(myStr, 0, 10);
  </code></pre>
  
  <p>However, this is a little over complicated for my needs.  I'd like a simple function, string in, unsigned long base 10 out.  Also, the error handling leaves much to be desired.</p>
  
  <p>The final possibility I have found is to use sscanf.</p>
  
  <pre><code>char *myStr; // Initalized to some value somehow.
  unsigned long n = 0;
  if(sscanf(myStr, "%lu", n) != 1) {
      //do some error handling
  }
  </code></pre>
  
  <p>Again, error handling leaves much to be desired, and a little more complicated than I'd like.</p>
  
  <p>The remaining obvious option is to write my own either a wrapper around one of the previous possibilities or some thing which cycles through the string and manually converts each digit until it reaches ULONG_MAX.</p>
  
  <p>My question is, what are the other options that my google-fu has failed to find?  Any thing in the C++ std library that will cleanly convert a string to an unsigned long and throw exceptions on failure?</p>
  
  <p>My apologies if this is a dupe, but I couldn't find any questions that exactly matched mine.</p>