Note that there are some explanatory texts on larger screens.

plurals
  1. POstringstream unsigned input validation
    primarykey
    data
    text
    <p>I'm writing part of program which parses and validates some user input in program console arguments. I choose to use stringstream for that purpose, but encounter a problem with unsigned types reading.</p> <p>Next template is intended for reading requested type from given string:</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; using std::string; using std::stringstream; using std::cout; using std::endl; template&lt;typename ValueType&gt; ValueType read_value(string s) { stringstream ss(s); ValueType res; ss &gt;&gt; res; if (ss.fail() or not ss.eof()) throw string("Bad argument: ") + s; return res; } // +template specializations for strings, etc. int main(void) { cout &lt;&lt; read_value&lt;unsigned int&gt;("-10") &lt;&lt; endl; } </code></pre> <p>In case type is unsigned and input string contains negative number I expect to see exception throw (caused by <code>ss.fail() = true</code>). But stringstream produces casted to unsigned type value (4294967286 in written sample).</p> <p>How can be this sample fixed to achieve desired behavior (preferable without fallback to c functions)? I understand that it can be done with simple first symbol check but I can put leading spaces for example. I can write own parser but don't believe that problem is so unpredictable and standard library unable to solve it.</p> <p>Functions hidden in deep of stringstream operators for unsigned types are strtoull and strtoul. They work in described manner but <em>mentioned functions are low-level</em>. Why stringstream do not provide some validation level? (I just hope I'm wrong and it does but some movements required to enable this).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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