C++ mystical infinite loop -


I have just started learning c ++ after coding with java. The code below takes input from the user and validates the input. The first piece asks for the number of voters, which should be a positive number. If I enter a negative number the way I expect the program to behave, it prints the error message and asks for input again. However, if I enter any other character, like I get an infinite loop in any alphabet I ask for input, and print error message. What am I doing wrong?

My code:

  #include & lt; Iostream & gt; using namespace std; Struct DataType {int numOfVoters = -1; Float prepsplug = -1; Float voting error = -1; }; Zero getUserInfo () {Data Data; While (data.numOfVoters == -1) {cout & lt; & Lt; "Enter the number of voters" & lt; & Lt; Endl; Cin & gt; & Gt; Data.numOfVoters; If (data.numOfVoters & lt; = 0) {data.numOfVoters = -1; Cout & lt; & Lt; "Invalid entry, please enter a number greater than zero." & Lt; & Lt; Endl; }} Whereas while (data.votingError == -1) {cout & lt; & Lt; "Enter percentage spread among candidates" & lt; & Lt; Endl; Cin & gt; & Gt; Data.votingError; If (data. Voting error & lt; = 0; data. Voting error & gt; = 1) {data.votingError = -1; Cout & lt; & Lt; "Invalid entry. Enter a number between 0 and 1." & Lt; & Lt; Endl; }} While (data.preSpread == -1) {cout & lt; & Lt; "Enter the spread of dispersal between two candidates." & Lt; & Lt; Endl; Cin & gt; & Gt; Data.preSpread; If (data. PreSpread & lt; = 0} data. PreSpread & gt; = 1) {data.preSpread = -1; Cout & lt; & Lt; "Invalid input. Enter a number between 0 and 1." & Lt; & Lt; Endl; }}} Int main () {getUserInfo (); Return 0; }   

Console:

  Enter the number of voters C Invalid entry, please enter a number greater than zero. Enter the number of voters Invalid entry, please enter a bigger number than zero Enter the number of voters Invalid entry, please enter a bigger number than zero ... ... ...    

if you cin> Will write; & Gt; Integer but can not represent an integer in the can, the input fails, ! Cin comes true, and the character will remain until you reset input status to error and consume incorrect characters.

There may be a proper investigation

  while (integervariable is not good value) {cout & lt; & Lt; "Prompt user:"; Cin & gt; & Gt; Integervariable; If something (cin.clear) in (! Cin) // input format; // clear the error flag cin.ignore (std :: numeric_limits & lt; std :: streamsize & gt; :: max), '\ n'); // Discard crap cout & lt; & Lt; "Quick error message \ n"; }}    

Comments

Popular posts from this blog

java - ImportError: No module named py4j.java_gateway -

python - Receiving "KeyError" after decoding json result from url -

.net - Creating a new Queue Manager and Queue in Websphere MQ (using C#) -