Hi! i was wondering how I could make sure that the user inputs the proper values in my code. I've been looking online and seen things like cin.good() and cin.fail() but the explanations aren't really straightforward and a little confusing. I was wondering if anyone could help me implement the proper input validation for my code. thanks so much!

#include <iostream>
using namespace std;

int main()
{
	double *num1ptr = new double;
	double *num2ptr = new double;
	char *oprptr = new char;
	double *solptr = new double;

	cout << "This program will add, subtract, multiply, or divide two" 
	<<" numbers inputted by the user." << endl;

	cout << "Please enter first number: ";
	cin >> *num1ptr;


	cout << "Please enter second number: ";
	cin >> *num2ptr;
	cout << "Enter the operation you would like to perform (to add use +,"
	<< " to subtract use -, to multiply use *, to divide use /): ";
	cin >> *oprptr;

	switch(*oprptr)
	{
	case '+':
		*solptr = *num1ptr + *num2ptr;
		break;
		
	case '-':
		*solptr = *num1ptr - *num2ptr;
		break;
		
	case '*':
		*solptr = *num1ptr * *num2ptr;
		break;
		
	case '/':
		*solptr = *num1ptr / *num2ptr;
		break;
	
	default:
		cout << "Invalid Operator Inputted" <<endl;
		break;
		
	}

	cout <<"Solution of "<<*num1ptr<<" "<<*oprptr<<" "<<*num2ptr
 	<<" = "<<*solptr<<endl;

}

What do you mean by proper values?

cin.bad() only returns true if the input is completely unusable. You're probably better off making sure that the input is good using something like isdigit() or isalpha(), depending on what you're looking for.

Also have a read of this http://www.daniweb.com/forums/thread90228.html

1) Forget the pointer crap, don't use it unless you really have to. Or if this is for practice then its ok for now.

A easy way to do it is like so :

template<typename T>
T getInput(const string& msg){
 cout << msg ;
 T var = T();
 //check if input failed
 while( !(cin >> var) ){
    cin.clear(); //reset the stream
    cin.ignore(256,'\n'); //read and discard the bad input
   //now try to read again
    cout << "\nBad input try again : "; 
 }
 return var;
}

int main(){
 int i = getInput<int>("Enter a number : ");
 float f = getInput<float>("Enter a number : ");
 char ch = getInput<char>("Enter a letter : ");
 string s = getInput<string>("Enter your name : ");
}
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.