a = 2 * 4
b = 5 * 4 - 1 + 5
c = a / b
c
Assume one expression per line (an expression is terminated by a new line).
If it is an assignment expression then add/update the symbol's value to
an internal table (i.e. dictionary). If it is not an assignment then
print the result to standard out. So the example above should print the
value of the variable c to standard output.
Your program should take two optional command line arguments, one to
specify a data source file another to request a help message.
calc [-h] [-f fn]
-h : print a usage message then exit
-g fn : open file fn and read expressions until eof is encountered
If no source file is specified then read from standard input (i.e. cin).
See roster.cc
for an example of how to read from a file or standard input.
<>
You are not required to define classes for this project (that will come
later) but I do want you to solve this problem using recursion (i.e. recursive descent). Your calculator must evaluate standard algebraic expressions (that is, using infix notation) with operators +, -, *, / and = (assignment). I have assigned
percedence and associativity to each operator in the table below.
You must also support the use of parenthesis to alter expression
evaluation order (i.e. to identify subexpressions). The
assignment operators are used to assign a value to variables, where a
variable is any continuous string of characters a-z.
While I want you to use recursive descent, it is up to you if you first
transform the infix notation to prefix or postfix.| Operators |
Operator |
Category |
Precedence |
Associativity |
|---|---|---|---|---|
| symbol, literal |
simple tokens |
primary |
5 |
n/a |
| - + |
negation, plus |
unary |
4 |
right-to-left |
| * / |
multiplicative |
binary |
3 |
left-to-right |
| + - |
additive |
binary |
2 |
left-to-right |
| = |
assignment |
binary |
1 |
right-to-left |
You may use any of the classes/templates from the STL. In particular you should
consider using the vector (#include <vector>, see the
Roster example
code referenced above) and map (#include <map>) types.
For example, assuming you represent values with
the builtin type double (you should) then you can define an associative map as
follows:
map table;
table["pi"] = 3.14159;
table["e"] = 2.71828;
...
// assume token is a string, value is a double
table[token] = value;
cin).
When assignment expressions are encountered you must record the value
in an internal symbol table but no output is to be generated. All
other expressions must be evaluated and the result written to standard
output (the object cout).make mkzipand verify it creates the file properly. Once you are certain everything is in order then execute
make turnin