T14 Calculator
T14 Calculator
Consider the simple calculator program on the following slides. The program reads
simple integer expressions from an input file and evaluates them:
Input: 17 + 43 Output: 17 + 43 = 60
67 - 14 67 - 14 = 53
89 * 12 89 * 12 = 1068
43 / 7 43 / 7 = 6
No more expressions.
This program also illustrates using the placement of function prototypes to restrict access
so that only functions that need to make calls can do so.
CS@VT June 2009 Intro Programming in C++ ©1995-2009 Barnette ND, McQuain WD & Kennan MA
Modular Decomposition Calculator 2
main
open I/O files While there are expressions to process close I/O files
NextExpression Print
. DoCalc Stop
.
.
.
.
.
CS@VT June 2009 Intro Programming in C++ ©1995-2009 Barnette ND, McQuain WD & Kennan MA
Simple Calculator Calculator 3
. . .
int main( ) {
int NextExpression(ifstream& In, int& Op1, char& Op, int& Op2);
void Print(int Op1, char Op, int Op2, int Val);
int Operand1, Operand2, Value = 0;
char Operator;
ifstream iFile;
iFile.open("Calculator.data");
while (iFile && Value != INT_MIN) {
Value = NextExpression(iFile, Operand1, Operator, Operand2);
if (Value == INT_MIN) {
cout << “No more expressions.” << endl;
iFile.close();
return 0;
}
Print(Operand1, Operator, Operand2, Value);
}
iFile.close(); // probably never executed, included for safety
return 0;
}
CS@VT June 2009 Intro Programming in C++ ©1995-2009 Barnette ND, McQuain WD & Kennan MA
Simple Calculator Calculator 4
int NextExpression(ifstream& In, int& Op1, char& Op, int& Op2) {
int DoCalc(int Op1, char Op, int Op2);
void GetOps(ifstream& In, int& Op1, char& Op, int& Op2);
if (In)
return DoCalc(Op1, Op, Op2); // evaluate if OK
else
return INT_MIN; // return flag if not
}
CS@VT June 2009 Intro Programming in C++ ©1995-2009 Barnette ND, McQuain WD & Kennan MA
Simple Calculator Calculator 5
CS@VT June 2009 Intro Programming in C++ ©1995-2009 Barnette ND, McQuain WD & Kennan MA