Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to add an input validation feature to this program in which the user assigns values to 4 variables. I currently have an if statement after each prompt for the user to enter in a value. Do I have to include this coded after every prompt or is there a way to simplify this? Not urgent, but curious.
int main()
{
	double ux, uy, vx, vy, angle_rad, angle_deg, angle;
	string error = "Error: please enter valid components for the vectors.";
	cout << "Please enter the x-component of vector u: ";
	cin >> ux;
	if (cin.fail())
	{
		cout << endl << error << endl << endl;
		return 1;
	}
	cout << endl << "Please enter the y-component of vector u: ";
	cin >> uy;
	if (cin.fail())
	{
		cout << endl << error << endl << endl;
		return 1;
	}
	cout << endl << "Please enter the x-component of vector v: ";
	cin >> vx;
	if (cin.fail())
	{
		cout << endl << error << endl << endl;
		return 1;
	}
	cout << endl << "Please enter the y-component of vector v: ";
	cin >> vy;
	if (cin.fail())
	{
		cout << endl << error << endl << endl;
		return 1;
	}


What I have tried:

I have tried placing only one string error at the end of all the prompts, however as soon as an invalid input is received, it will still show the other cout displays before displaying the string error.
Posted
Updated 19-Sep-16 21:34pm
v2
Comments
Peter_in_2780 20-Sep-16 2:08am    
Looks very much like a case for a subroutine.

If you want to break upon an invalid input you have to check a condition at each input. But you can use a function for each input that prints the error message:

C++
#include <float.h>

bool getDouble(double &val, const char *msg, double min = DBL_MIN, double max = DBL_MAX)
{
    bool bValid = true;
    cout << endl << msg;
    cin >> val;
    if (cin.fail())
    {
        cout << endl << "Error: please enter valid components for the vectors." << endl << endl;
        bValid = false;
    }
    else if (val < min)
    {
        cout << endl << "Error: Value is too small" << endl << endl;
        bValid = false;
    }
    else if (val > max)
    {
        cout << endl << "Error: Value is too large" << endl << endl;
        bValid = false;
    }
    return bValid;
}
</float.h>

Then call this function for each input:
C++
if (!getDouble(ux, "Please enter the x-component of vector u: "))
    return 1;
if (!getDouble(uy, "Please enter the y-component of vector u: "))
    return 1;
// ...
 
Share this answer
 
Comments
CPallini 20-Sep-16 3:31am    
5.
Also note there is room for some OOP in your scenario. You could define a bidimensional vector class and overload the input (and possibly) output operators for it.
 
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