Hi all,
I am a beginner to C++ and am having problems with data validation in a project. The program is a oylmpic diving score program and is working ok only for when I input an invalid character the for loop seems to continusal run. Is there an easy for me to fix this so that I can just output to the user "Invalid character"??

Please see below section of code...

//User input
                cout<<"\nPlease enter first judges score : \n\n";
                cin>>judge1;
                            //While loop for data validation
                            while (judge1<0 || judge1>6)
                            {
                               cout<<"Invalid score, must be in the range 0.0 to 6.0\n\n";
                               cout<<"Please reenter\n";
                               cin>>judge1;
                               }

My usual advice is to read all user input as a string; if you want a numeric input, convert the string. Otherwise there is some cleanup of cin that you can do. There must be countless examples of this that can by found by searching this forum.

Use this :

#include <iostream>
#include <string>
using namespace std;

int getInt(const string& messageBeforeInput){
   cout << messageBeforeInput;
   int result = 0;
   while(! (cin >> result) ){ //check for bad input
      cout  << messageBeforeInput ;
      cin.clear();  //clear the stream bits
      while(cin.get() != '\n') continue; //get rid of the junk
   }
  return result;
}
bool failsRange(const int value, const int min, const int max){
	 return value < min || value > max;
}
int main()
{
   int value = -1;

    while( failsRange(value,0,100) )
          value = getInt("Please enter a number :" );

	cout << value << endl;

  return 0;
}

I agree with Dave, depending on what you've learned so far, accept all input as a string and use atoi and atof string functions to convert them (So your prog wont freak out if letters are entered into an int or double variable)

Thanks a million for all your help, I think I'll try read them as string and then converting, seems like the simplest option!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.