cin is a strange animal. Here is the corrected program. Polish of the I/O I leave to you. cin.fail will not help unless you process it. remember that you can do a
cin >> x >> y >> z ;
cin returns an istream object whether it is successful or not so...
while(cin >> x)
is always true because cin returned itself
Hope this helps.
Jeronimo
CODE
#include <math.h>
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
double firstOperand;
char operation;
double secondOperand;
double result;
double add(double,double);
double sub(double,double);
double mult(double,double);
double div(double,double);
double exp(double,double);
char ch;
bool keep_going = 1;
int main()
{
while (keep_going)
{
cout << "Enter expression (Q to quit): ";
cin >> firstOperand;
if (cin.fail()) // could not assign to int
{
cin.clear(); // end error condition
cin >> ch; // get one char
}
if( (ch=='q') || (ch=='Q') ) { break; }
cout << "\n\tEnter Operation: ";
// cin >> operation // plus causes problems (not +, PLUS)
operation = _getche();
if( (operation=='q') || (operation=='Q') ) { break; }
cout << "\nSecond Expression: ";
cin >> secondOperand;
if (cin.fail())
{
cin.clear();
cin >> ch;
}
if( (ch=='q') || (ch=='Q') ) { break; }
if (operation == '+') {
result = add(firstOperand,secondOperand);
} else if (operation == '-') {
result = sub(firstOperand,secondOperand);
} else if (operation == '*') {
result = mult(firstOperand,secondOperand);
} else if (operation == '/') {
if (secondOperand == 0) {
cout << "\n\nError: Cannot divide by zero\n\n" << endl;
//cout << "Enter expression (^D to quit): ";
continue;
} result = div(firstOperand,secondOperand);
} else if (operation == '^') {
result = exp(firstOperand,secondOperand);
} else {
cout << "Invalid operator: " << operation << endl;
continue;
}
cout << "\n\tThe result is: " << result << endl;
//cout << "Enter expression (^D to quit): ";
}
cout << "\n\n\tThank you for using the calculator program.\n\n\t";
system("pause");
return 0;
}
double add(double a, double b)
{
return a + b;
}
double sub(double a, double b)
{
return a - b;
}
double mult(double a, double b)
{
return a * b;
}
double div(double a, double b)
{
return a / b;
}
double exp(double a, double b)
{
return pow(a,b);
}