Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I check if the user has entered valid value?
    text
    copied!<p>I'm writing a project and I have to check if the user has entered a valid value for specific things. For example, first case is to check whether he inputted an integer, which is no longer than 6 length and >0. I am working with struct, so my code is this:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int dolzina_int(int vlez); int main() { struct pole{ int sifra; // sifra na artiklot string opis; // opis na artiklot float cena; // edinecna cena int vlez_kol; // vlezna kolicina int izlez_kol; // izlezna kolicina float dan_stapka; // danocna stapka float iznos; // iznos int datum; // datum na vlez i izlez (GGMMDD) }artikli[100]; // maksimalen broj na artikli e 100 for (int i = 0; i &lt; 5; i++){ cin &gt;&gt; artikli[i].sifra; while(!(cin &gt;&gt; artikli[i].sifra) || (artikli[i].sifra &lt; 0 || (dolzina_int(artikli[i].sifra) &gt; 6))) { cout &lt;&lt; "Error" &lt;&lt; endl; cin.clear(); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); } } return 0; } // funkcija za dolzina na integer int dolzina_int(int vlez){ int dolzina = 1; while(vlez &gt; 0){ dolzina++; vlez /= 10; } return dolzina; } </code></pre> <p>So, my code seems to work, the first part, it does check if it's >6 or &lt;0, but the second else if, it doesn't work properly to check if it's an integer or not. So my question is the following, how can i make sure that it's an integer value that the user enters and how can I make sure the length of integer is not >6 or the value is &lt;0 and meanwhile, if it is, to make him re-enter it, and also check the newly entered value, as my code doesn't do that currently.</p> <pre><code>for (int i = 0; i &lt; 5; i++){ artikli[i].sifra = 1; do{ cout &lt;&lt; "Enter a code: "; while(!(cin &gt;&gt; artikli[i].sifra)){ cin.clear(); cin.ignore(); cout &lt;&lt; "Invalid entry. Enter a new value: "; } }while(artikli[i].sifra &gt; 0 &amp;&amp; dolzina_int(artikli[i].sifra) &gt; 6); } </code></pre>
 

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