3

In K&R we have managed to create an RPN.

The exercise now is to:

Add commands for handling variables, (It's easy to provide twenty-six variables with single letter names.) Add a variable for the most recently printed value.

So this is meant to act somewhat like the Python interpreter, where we can do:

>>>5
>>>_ (where _ prints 5)
>>>_ + 5 (which prints 10)

or A = 5 _ + A (which prints 10)

and so on, but I'm not so sure about how I want to go about it in C. I just feel stumped.

BSMP
  • 4,596
  • 8
  • 33
  • 44
lamenuts
  • 31
  • 1

2 Answers2

2

Create a 26th variable. Any time you print something, write that value into the 26th variable. When they use _ (or whatever name you choose) read from that variable.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • I'm expected to be able to read the variable using the variable name of choice: Given A = 5, when I enter "A", I expect it to print 5, or B = 6, B prints 6, _ prints the last variable, A + B prints 11, _ + 4 would print 15, and so on. – lamenuts Jul 09 '10 at 06:56
  • it is not clear what is expected. It makes sense to use variables as operands. However, so far in that chapter the necessary tools are not given in order to make that an easy exercise. I think the answer's suggestion is ok. – Ely Aug 26 '15 at 11:29
  • frankly speaking, I don't really even know what the question's meaning, It 's like trying to answering a question that the question's meaning is unclear....so anyone could explain, I don't need the solution, but I don't understand the question...thx! – Thomas Mar 23 '21 at 15:16
0

This is first step of building a command line calculator I guess.

Parse the input string for operands and operator. Map the operator to a enum

enum operator { TYPE_ADD, TYPE_SUBTRACT,TYPE_MAX);

Call function to compute result

  int    calculate(int i_op1, int i_op2, operator e_operator)
           {
              /*Use switch case to calculate result*/
           }

Save this result into a variable. In input in the string is equal to "_" then use this as first input to the function calculate.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Praveen S
  • 10,355
  • 2
  • 43
  • 69