Click here to Skip to main content
15,893,486 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello I have a piece of code that calculates scores. I want to put an Input Validation but I couldn't figure it out. Can you help me ?

C++
<pre>
int main()
{
	//DECLARATIONS
	int	 score1, score2, score3, rounds; 
	bool needInput = true;
	double total=0.0;
	double average = 0.0; // average score of an archer
	
	do
	    {
			for(rounds=1; rounds<=4; rounds++)
			{
				cout << "Enter Archer's Score:";
				cin >> score1;	
				
				if (score1 > 0, score1 < 60)
				{
					needInput=false;
				}
				else if(!cin)
				{
					cout << "The entry must be an integer.";
				}
				else
				{
					cout << "The entry must be between 0 and 60.";
				}
			}
			if(needInput=false)
			{
					total = total + score1;
				average = total / 3;
				cout << "Total Score=" << total << endl;
				cout << "Average Score=" << average << endl;
			}
			else
			{
				cout << "You entered invalid entry. You need to enter again.";
			}
			return 0;	
		}while (needInput);

}


What I have tried:

I tried to put do-while loop but It doesn't restart when the user inputs invalid input.
Posted
Updated 24-Jan-17 0:13am
Comments
[no name] 22-Jan-17 19:12pm    
What do you think "if(needInput=false)" is doing? Stepping through your code using a debugger would tell you what the problem is.

Comment out the return just about the while statement and see what that does for you.
 
Share this answer
 
change the code from
C++
if (needInput = false)


to
C++
if (needInput == false)


that should work!
 
Share this answer
 
When you read an int from cin, it will simply get the input up to (and not including) the first character that can not be interpreted as part of an integer. If the first character of the input is already invalid, the result will be simply 0, but the state of cin will not change. Therefore, !cin does not indicate invalid input at all!

If you want to test the validity of user input, and expect that it may be wrong, you must read the input as string. Then you can examine the string to find out whether it is valid or not.

(also: follow the advice given in solution 2)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900