Note that there are some explanatory texts on larger screens.

plurals
  1. POMalfunctioning type-casting of string to unsigned int
    primarykey
    data
    text
    <p>I'm having a annoying problem with a C++ function that I wrote and whose purpose is to validate de user input. The function reads the user input, verifies if it's a number and, if so, if it is in the range [min, max].</p> <p>The problem occurs when I invoke the template function with a unsigned type, like <code>size_t</code>, and the input is a negative number. The string stream converts the string to something like 4294967291. I can see that the program is converting the data to a value near de maximum value of the unsigned data type (defined in the numeric_limits header) but my question is why, since the <code>if</code> statement should stop at <code>sstream &gt;&gt; value</code>?</p> <p>My code:</p> <pre><code>template &lt;class T&gt; T getNumberInput(std::string prompt, T min, T max) { std::string input; T value; while (true) { try { std::cout &lt;&lt; prompt; std::cin.clear(); std::getline(std::cin, input); std::stringstream sstream(input); if (input.empty()) { throw EmptyInput&lt;std::string&gt;(input); } else if (sstream &gt;&gt; value &amp;&amp; value &gt;= min &amp;&amp; value &lt;= max) { std::cout &lt;&lt; std::endl; return value; } else { throw InvalidInput&lt;std::string&gt;(input); } } catch (EmptyInput&lt;std::string&gt; &amp; emptyInput) { std::cout &lt;&lt; "O campo não pode ser vazio!\n" &lt;&lt; std::endl; } catch (InvalidInput&lt;std::string&gt; &amp; invalidInput){ std::cout &lt;&lt; "Tipo de dados inválido!\n" &lt;&lt; std::endl; } } } </code></pre> <p>Thank you for your time!</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.
 

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