data validation issue

hello everyone, first post here probably of many.
i've been working on one of my final programs for my intro c++ class.
everything is working fine except for the data validation step and i am havign trouble figuring out why.
i have only attached the void function that is giving me problems.
if you need more let me know.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void getScore(double& scoreA)
{
	double scoreB;
	cout<<"Please enter judge's score: ";
	cin>>scoreB;

	if (scoreB<0 || scoreB>10 || static_cast<double>(scoreB) != static_cast<int>(scoreB))
	{
		cout<<"This is an invalid score, please try again."<<static_cast<double>(scoreB)<<static_cast<int>(scoreB);
		cin.clear();
		getScore(scoreB);
	}
	else
		scoreA=scoreB;
}

the code should input a score from the user and check to make sure it is an integer between 0 and 10. the way i have it, it would not invalidate a character, which isn't necessary but would make it a bit neater.
any help is appreciated. thanks.
i seem to have fixed my problems by changing it to this:
1
2
3
4
5
6
7
8
	while (scoreB<0 || scoreB>10 || scoreB != static_cast<int>(scoreB))
	{
		cout<<"This is an invalid score, please try again."<<endl;
		getScore(scoreB);
	}

		scoreA=scoreB;
}


this works, but if i enter a char i get an infinite loop. but like i said that part is not required for the program, it would just be nice.
i also get an error message about a loss of data converting from double to int, but this was what i wanted to validate the integer, but the error message is leading me to believe that there is another method.
Your first approach as you may have figured out by yourself had a static casting to itself (scoreB is double and a casting to double does not change it a bit).

You just want to see if scoreB is int right?
Well if you define scoreB as int cin would take just the integral part of your real number that is if you enter
1.2, scoreB would be 1. I am not sure you want this but you can have it mind. No validating user input here needed (at least if user inputs a number and not a alphanumeric).

Also another point is that if you define a variable as int you can get integral part of scoreB by using:
int score = scoreB;. No big gain here since the last approach of course.

Also if your compiler gives you an error (meaning you cannot compile the program) for this casting you can either change the level of error detection of your compiler or just use another int variable where you can store scoreB integral part and then compare.

As for the case where user enters alphanumeric I don't know why it goes to infinite loop but you can overcome this if you handle your input as string. Some extra steps are required here in this case but you are covered for all cases.

If you are interested in this see http://www.cplusplus.com/forum/beginner/57855/
Topic archived. No new replies allowed.