C++/what must it do to make validation to the input here
Expert: Ralph McArdell - 3/16/2007
QuestionHi how are you Ralph
I hope you're good
I want to ask in a problem faced me when i was coding a simple calculator ant this is its code
#include<iostream>
#include<cmath>
using namespace std;
int main()
{bool c=1,z=1;
double op1=0,op2=0;
char x='1',y='1';
while(c==1)
{
cout<<"Enter The first Operation-> OP1 sign OP2: ";
cin>>op1;
cin>>x;
z=1;
while(z==1)
{
if(x!='c') cin>>op2;
switch (x)
{case '+':
op1=op1+op2;
cout<<"
Result = "<<op1<<endl;
break;
case '-':
op1=op1-op2;
cout<<"
Result = "<<op1<<endl;
break;
case '*':
op1=op1*op2;
cout<<"
Result = "<<op1<<endl;
break;
case '/':
if(op2==0) cout<<"
math error
a";
if(op2!=0)
{op1=op1/op2;}
cout<<"
Result = "<<op1<<endl;
break;
case 'p':
op1=pow(op1,op2);
cout<<"
Result = "<<op1<<endl;
break;
case 'P':
op1=pow(op1,op2);
cout<<"
Result = "<<op1<<endl;
break;
default :
cout<<"
Invalid Operation";
cout<<"
Result = "<<op1<<endl;
break;
}
if(x!='c')
{cout<<"Enter The next Operation-> sign OP2 (or Q to quit, c to clear, c to clear): ";
cin>>x;
if(x=='q'||x=='Q')
{return 0;}
if(x=='c'||x=='C')
{
cout<<"
Memory is Cleared";
cout<<"
Result = "<<op1<<endl<<endl;
break; }
}
}
}
return 0;}
The problem is how can I check if the user input in op1 or op2 only numbers and not any thing else because if the user input was any thing else the calculator will output wrong result of course
And at the end I want to thank you because of your beg effort which you do to solve the problems
AnswerYou are reading the values as doubles. If you enter a double value in a format that is not supported then you should get a stream failure, that is std::cim.fail() will return true. A stream failure indicates a non-fatal error, usually a formatting error as is the case here. You can use this to check if the value is as expected and take appropriate action, for example you might ask for the operand again:
#include <iostream>
#include <limits>
// Main program entry point
int main()
{
double op1(0.0);
bool bad(false);
do
{
bad = false;
std::cin >> op1;
if ( std::cin.fail() )
{
std::cerr << "Please enter a valid number "
"for the first operand.\n";
bad = true;
std::cin.clear();
std::cin.ignore(std::numeric_limits<int>::max(),'\n');
}
}
while ( bad );
std::cout << "First operand: " << op1 << std::endl;
}
You will notice that after reading in op1 I check to see if the std::cin stream is in a failed state. If it is I write an error message to std::cerr and set the bad flag so the loop will continue round another time. However, before doing so I have to clean up a bit. First I reset all the stream flags (I could have used another form of clear to just clear the failed flag) and then called ignore to read any remaining characters on the input line.
In fact testing fail() also checks the bad stream flag, which is set if the stream is in an unrecoverable state. So after checking fail I should also check for cin being bad and if so perform some more drastic action - displaying a different error and returning immediately for example:
if ( std::cin.fail() )
{
if ( std::cin.bad() )
{
std::cerr << "FATAL ERROR: Console input "
"in unrecoverable state\n.";
return 1;
}
// ...
Of course the example I have shown is probably not quite what you want. This is because the data is probably not handed over to your program until a whole line has been entered on the console. In this case the user will most likely have typed the whole expression in before your program detects an error in say the first operand.
If you do not skip over the rest of the pending input (e.g. by calling ignore as above) then the next thing read is the operator followed by the second operand - which is not helpful if trying to get the user to re-enter the fist operand!
The easiest course of action is probably to say that any error trashes the whole expression and the user will have to re-enter the whole thing.
Now we can just expand the re-entry loop to handle the other parts of the expression:
double op1(0.0);
char operation( '1' );
double op2(0.0);
bool bad(false);
do
{
bad = false;
std::cin >> op1;
bad = std::cin.fail();
if ( !bad )
{
std::cin >> operation;
bad = std::cin.fail();
// if not bad then check operation character is valid.
// if not then set bad to true
}
if ( !bad )
{
std::cin >> op2;
bad = std::cin.fail();
}
if ( bad )
{
if ( std::cin.bad() )
{
std::cerr << "FATAL ERROR: Console input "
"in unrecoverable state\n.";
return 1;
}
std::cerr << "Please enter a valid expression.\n";
bad = true;
std::cin.clear();
std::cin.ignore(std::numeric_limits<int>::max(),'\n');
}
}
while ( bad );
As you can see after each item is input I store the result of std::cin.fail() in the bad flag and only proceed to read more input if bad is not true. At the end of the loop I perform error handling if bad is true as before, with a more appropriate error message for the expression re-entry request. I changed your x operator character variable name to operation (as the name operator is a C++ reserved word!), as it seems more descriptive to me. In addition to setting bad on stream state you should probably also check that the returned character is one you were expecting (i.e. one of +-*/p).
The above code traps most errors unless there are more characters entered than used, as in the following input:
123.456+987-098
The user erroneously entered a minus sign instead of a decimal point. However this will be interpreted as:
op1 = 123.456
operator = +
op2 = 987
The remaining characters:
-098
are not used BUT left in the stream buffer for std::cin, so will be processed next if you request for more input from std::cin.
I shall leave it to you to tidy this up if you feel the need.
Finally I should point out that the code I show is for example and demonstration purposes only and not necessarily of production quality. You may need to do more work to fit such ideas into your own code.
Hope this helps.