如何进行输入验证 [英] How do I put an input validation

查看:78
本文介绍了如何进行输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一段代码来计算分数。我想进行输入验证,但我无法弄清楚。你能帮助我吗?



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 ?

<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);

}





我的尝试:



我试图把do-while循环但是当用户输入无效输入时它没有重启。



What I have tried:

I tried to put do-while loop but It doesn't restart when the user inputs invalid input.

推荐答案

注释掉关于while语句的返回,看看它为你做了什么。
Comment out the return just about the while statement and see what that does for you.


更改代码来自

change the code from
if (needInput = false)





to



to

if (needInput == false)





应该有效!



that should work!


当你读<$ c时$ c> int 来自 cin ,它只会输入(并且不包括)第一个不能被解释为部分的字符一个整数。如果输入的第一个字符已经无效,结果将只是0, cin 的状态不会改变。因此,!cin 根本不表示输入无效!



如果要测试用户的有效性输入,并期望它可能是错误的,您必须将输入读取为字符串。然后你可以检查字符串以确定它是否有效。



(同时:按照解决方案2中给出的建议)
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)


这篇关于如何进行输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆