Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Another version...</p> <p>Use <a href="http://en.cppreference.com/w/cpp/string/byte/strtol" rel="noreferrer"><code>strtol</code></a>, wrapping it inside a simple function to hide its complexity :</p> <pre><code>inline bool isInteger(const std::string &amp; s) { if(s.empty() || ((!isdigit(s[0])) &amp;&amp; (s[0] != '-') &amp;&amp; (s[0] != '+'))) return false ; char * p ; strtol(s.c_str(), &amp;p, 10) ; return (*p == 0) ; } </code></pre> <h3>Why <code>strtol</code> ?</h3> <p>As far as I love C++, sometimes the C API is the best answer as far as I am concerned:</p> <ul> <li>using exceptions is overkill for a test that is authorized to fail</li> <li>the temporary stream object creation by the lexical cast is overkill and over-inefficient when the C standard library has a little known dedicated function that does the job.</li> </ul> <h3>How does it work ?</h3> <p><code>strtol</code> seems quite raw at first glance, so an explanation will make the code simpler to read :</p> <p><code>strtol</code> will parse the string, stopping at the first character that cannot be considered part of an integer. If you provide <code>p</code> (as I did above), it sets <code>p</code> right at this first non-integer character.</p> <p>My reasoning is that if <code>p</code> is not set to the end of the string (the 0 character), then there is a non-integer character in the string <code>s</code>, meaning <code>s</code> is not a correct integer. </p> <p>The first tests are there to eliminate corner cases (leading spaces, empty string, etc.).</p> <p>This function should be, of course, customized to your needs (are leading spaces an error? etc.).</p> <h3>Sources :</h3> <p>See the description of <code>strtol</code> at: <a href="http://en.cppreference.com/w/cpp/string/byte/strtol" rel="noreferrer">http://en.cppreference.com/w/cpp/string/byte/strtol</a>.</p> <p>See, too, the description of <code>strtol</code>'s sister functions (<code>strtod</code>, <code>strtoul</code>, etc.).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload