Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The compiler is pretty unlikely to manage to throw out the conversion no matter what. Exceptions are just the icing on the cake. If you want to optimize this, you'll have to write your own parser to recognize the format for a float. Use regexps or manually parse, since the pattern is simple:</p> <pre><code>if ( s.empty() ) return false; string::const_iterator si = s.begin(); if ( *si == '+' || * si == '-' ) ++ si; if ( si == s.end() ) return false; while ( '0' &lt;= *si &amp;&amp; *si &lt;= '9' &amp;&amp; si != s.end() ) ++ si; if ( si == s.end() ) return true; if ( * si == '.' ) ++ si; if ( ( * si == 'e' || * si == 'E' ) &amp;&amp; si - s.begin() &lt;= 1 + (s[0] == '+') + (s[0] == '-') ) return false; if ( si == s.end() ) return si - s.begin() &gt; 1 + (s[0] == '+') + (s[0] == '-'); while ( '0' &lt;= *si &amp;&amp; *si &lt;= '9' &amp;&amp; si != s.end() ) ++ si; if ( si == s.end() ) return true; if ( * si == 'e' || * si == 'E' ) { ++ si; if ( si == s.end() ) return false; if ( * si == '-' || * si == '+' ) ++ si; if ( si == s.end() ) return false; while ( '0' &lt;= *si &amp;&amp; *si &lt;= '9' &amp;&amp; si != s.end() ) ++ si; } return si == s.end(); </code></pre> <p>Not tested… I'll let you run through all the possible format combinations ;v)</p> <p>Edit: Also, note that this is totally incompatible with localization. You have absolutely no hope of internationally checking without converting.</p> <p>Edit 2: Oops, I thought someone else already suggested this. <code>boost::lexical_cast</code> is actually deceptively simple. To at least avoid throwing+catching the exception, you can reimplement it somewhat:</p> <pre><code>istringstream ss( s ); double d; ss &gt;&gt; d &gt;&gt; ws; // ws discards whitespace return ss &amp;&amp; ss.eof(); // omit ws and eof if you know no trailing spaces </code></pre> <p>This code, on the other hand, has been tested ;v)</p>
 

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