-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lab1.cpp
94 lines (83 loc) · 1.59 KB
/
Lab1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
Interpreter for the Simplified Infix Arethmetic Expresion in C
*/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int Exp(), Term(), Exp2(int), Term2(int), Fact();
ifstream testfile;
// Main Function
int main(int argc, char* argv[])
{
testfile.open(argv[1]);
// Print sigle digit result
if(testfile.is_open())
{
cout << "Result = " << Exp() << '\n';
testfile.close();
}
else
{
cout << "Unable to open file";
}
return 0;
}
// Starts the Interpreter
int Exp()
{
// S or starting point of the language
return Exp2(Term());
}
// returns the result of a Term
int Term()
{
return Term2(Fact());
}
// Determines if the next symbol is a + or -
// may only return inp in some cases
int Exp2(int inp)
{
int result = inp;
char a;
testfile.get(a);
if(a != EOF)
{
if(a == '+')
{
result = Exp2(result + Term());
}
else if(a == '-')
{
result = Exp2(result - Term());
}
}
return result;
}
// determines is the next character is a * or /
// if result is + or - the char is put back into the input stream
// may only return inp
int Term2(int inp)
{
int result = inp;
char a;
testfile.get(a);
if(a != EOF)
{
if (a == '*')
result = Term2(result * Fact());
else if (a == '/')
result = Term2(result / Fact());
else if (a == '+' || a == '-')
testfile.putback(a);
}
return result;
}
// returns a digit or a symbol(+-/*). also the first function to return a result
int Fact()
{
char a;
testfile.get(a);
return (a - '0');
}