Ne.app NeANT
The Ne.app NeANT User module of the NeANT distribution.
Main Page
Related Pages
Topics
Namespaces
Data Structures
Files
File List
Globals
EXTERNAL_HEADERS
RSL
examples
tutorial
calc.cpp
Go to the documentation of this file.
1
29
#include <vector>
30
#include <stack>
31
#include <iostream>
32
33
#include <
examples.h
>
34
35
36
// Simulate the behavior of a simple integer calculator.
37
38
struct
Calculator
39
{
40
int
currentMemory
()
const
{
41
return
data_.top ();
42
}
43
44
void
pushOperand
(
int
value
) {
45
data_.push (
value
);
46
}
47
48
void
doOperator
(
char
);
49
50
private
:
51
52
std::stack<int, std::vector<int, std::allocator<int> > > data_;
53
};
54
55
56
void
Calculator::doOperator
(
char
theOp)
57
{
58
int
tmp
= data_.top ();
59
data_.pop ();
60
61
switch
(theOp) {
62
case
'+'
:
tmp
= data_.top () +
tmp
;
break
;
63
case
'-'
:
tmp
= data_.top () -
tmp
;
break
;
64
case
'*'
:
tmp
= data_.top () *
tmp
;
break
;
65
case
'/'
:
tmp
= data_.top () /
tmp
;
break
;
66
case
'%'
:
tmp
= data_.top () %
tmp
;
break
;
67
}
68
69
data_.pop ();
70
data_.push (
tmp
);
71
}
72
73
74
int
main
()
75
{
76
std::cout <<
"Calculator example program, from Chapter 8\n"
77
<<
"Enter a legal RPN expression, end with p q (print and quit)"
78
<< std::endl;
79
80
Calculator
calc;
81
82
for
(
char
c
; std::cin >>
c
; ) {
83
84
int
intval;
85
86
switch
(
c
) {
87
case
'0'
:
case
'1'
:
case
'2'
:
case
'3'
:
case
'4'
:
88
case
'5'
:
case
'6'
:
case
'7'
:
case
'8'
:
case
'9'
:
89
std::cin.putback (
c
);
90
std::cin >> intval;
91
calc.
pushOperand
(intval);
92
break
;
93
case
'+'
:
case
'-'
:
case
'*'
:
case
'/'
:
case
'%'
:
94
calc.
doOperator
(
c
);
95
break
;
96
case
'p'
:
97
std::cout << calc.
currentMemory
() << std::endl;
98
break
;
99
case
'q'
:
100
std::cout <<
"End calculator program"
<< std::endl;
101
return
0;
// quit program
102
}
103
}
104
105
return
0;
106
}
c
#define c
Definition
17.names.cpp:111
tmp
#define tmp
Definition
17.names.cpp:553
value
T value(const T &val)
Definition
26.valarray.cassign.cpp:139
main
int main()
Definition
calc.cpp:74
examples.h
Calculator
Definition
calc.cpp:39
Calculator::pushOperand
void pushOperand(int value)
Definition
calc.cpp:44
Calculator::doOperator
void doOperator(char)
Definition
calc.cpp:56
Calculator::currentMemory
int currentMemory() const
Definition
calc.cpp:40
Generated by
1.9.8