(E) Pocket calculator with a bit more than four operationsΒΆ

Goal: I will learn to use function pointers.

Instructions: Retrieve the code template: templates/09/calculator/ -> student/09/calculator/.

a) Explore data structures struct Command and const vector<Command> COMMANDS implemented in the code template. They comprise all the commands that the pocket calculator under implementation will be able to execute. Executing a command is managed by using the data in the structs.

Implement the missing parts such that the program will work as:

calculator> + 1 1
2.00
calculator> PLUS 1 1
2.00
calculator> plus 1 1
2.00
calculator> AdDiTiOn 1 1
2.00
calculator> + 1 2 3
Error: wrong number of parameters.
calculator> + 1
Error: wrong number of parameters.
calculator> + 1 two
Error: a non-number operand.
calculator> + one two
Error: a non-number operand.
calculator> stop now
Error: wrong number of parameters.
calculator> hey stop
Error: unknown command.
calculator> stop
Thanks and see you later!

Tips for completing the assignment:

  • Explore the content of files calculations.cpp and calculations.hh before implementing code. You need not change these files at this phase.
  • The idea of the solution is similar to that in the example examples/04/datadrivenprogramming (that was considered on round 4 at Data driven programming).
  • Command structs comprise the information needed in executing a command. The purpose is to go through the command structs in the command vector and process according to the values in a struct field. You need to check, if the input command is valid, if the amount of parameters is correct, and if the operands can be converted into a valid data type. When needed, an error message will be printed as in the example execution. Finally, if the whole input is valid, the given operation will be performed by using function pointer stored in the action field.
  • You can change a single letter to its upper-case counterpart by calling function toupper that was introduced in the material at 3.5.

b) As a new operation, insert exponentiation in the calculator. Like the existing operations, it will take two parameters: base and exponent. The commands that execute this operation are ^, POWER, and EXP.

Example on program execution:

calculator> ^ 2 3
8.00
calculator> PoWeR 2 3
8.00
calculator> exp 1 1
1.00
calculator> Exp 1 2 3
Error: wrong number of parameters.
calculator> ^ 1
Error: wrong number of parameters.
calculator> ^ 1 two
Error: a non-number operand.
calculator> quit
Thanks and see you later!

A+ presents the exercise submission form here.