c++ - Allow only numbers from 0 to 1 -


I have this down but if I put a letter, I get an infinite loop.

What is the proper way to do this is that it only accepts 0 to 1 numbers, and no letters or other characters. It should accept numbers 0.5 between 0 and 0.5 as 0.5

  int alphaval = -1; Cout & lt; & Lt; Enter the number between 0 and 1: "; Cin & gt; & Gt; Alphaval; While (alphaval & lt; 0; alphaval & gt; 1) {cout & lt; & Lt; "Invalid entry! Please enter a valid value:"; Cin & gt; & Gt; Alphaval; }    

Note that will be in std :: cin Bad situation if you enter unexpected type values ​​(such as when expected interfaces are expected). If a stream is in an invalid state, it will also fail to read valid inputs, and the loop will run infinitely, it seems that is your case, so the stream needs to clear the and stream, Because the stream did not have invalid input, you have to leave it (using the ignore function):

  double alpha; // It should be double or float (according to your requirement) cin & gt; & Gt; Alphaval; While (alphaval & lt; 0; alphaval & gt; 1) {cout & lt; & Lt; "Invalid entry! Please enter a valid value:"; // fix cin.clear (); // Clear bad flags! Cin.ignore (std :: numeric_limits & lt; std :: streamsize & gt; :: max (), '\ n'); // Drop bad input cin & gt; & Gt; Alphaval; // read fresh! }   

& lt; Limit & gt; std :: numeric_limits & lt; & Gt; . Include the title file for .

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -