-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformatEvalString.cpp
113 lines (104 loc) · 2.09 KB
/
formatEvalString.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include"formatEvalString.h"
extern int priList[];
formatEvalString::formatEvalString(string s)
{
charList = s.c_str();
format();
}
formatEvalString::~formatEvalString() {}
double formatEvalString::getEvalListAt(int i, int j)
{
return evalList[i][j];
}
// + - * / ^ ( ) 编码为 1 2 3 4 5 6 7;
int formatEvalString::encodeOpt(char ch)
{
switch (ch)
{
case '+': return 1; break;
case '-': return 2; break;
case '*': return 3; break;
case '/': return 4; break;
case '^': return 5; break;
case '(': return 6; break;
case ')': return 7; break;
default:
break;
}
}
void formatEvalString::format()
{
int i = 0;
int j = 0;
char ch;
string s;
int flag = 0;
while ((ch = charList[i]) != '\0')//遍历整个表达式字符数组;
{
//如果是数字,按顺序把字符转换成double型存在evallist中,标志位记为0;
if (ch <= '9' && ch >= '0' || ch == '.' && flag != 1)
{
s.append(1, ch);
if (!(charList[i + 1] <= '9' && charList[i + 1] >= '0') && !(charList[i + 1
] == '.'))
{
evalList[0][j] = 0;
evalList[1][j] = stringToNumber(s);
j++;
s.clear();
}
}
//如果是负数
else if (ch == '-' && charList[i + 1] <= '9' && charList[i + 1] >= '0' &&
!(charList[i - 1] <= '9' && charList[i - 1] >= '0') )
{
flag = 1;
s.append(1, ch);
if (!(charList[i + 1] <= '9' && charList[i + 1] >= '0') && !(charList[i + 1
] == '.'))
{
evalList[0][j] = 0;
evalList[1][j] = stringToNumber(s);
j++;
s.clear();
flag = 0;
}
}
//如果是+ - * / ^, 编码为 1 2 3 4 5 标志位记为 1;
else if (ch == '+' || (ch == '-' && (charList[i - 1] <= '9' && charList[i - 1] >= '0'))
|| ch == '*'
|| ch == '/' || ch == '^')
{
evalList[0][j] = 1;
evalList[1][j] = encodeOpt(ch);
j++;
}
else if (ch == '(')
{
evalList[0][j] = 2;
j++;
}
else if (ch == ')')
{
evalList[0][j] = 3;
j++;
}
else if (ch == ' ' || ch == '\\t' || ch == ';')
{
;
}
else
{
throw("error: unknow syntax");
}
i++;
}
evalList[0][j] = 4;
}
double formatEvalString::stringToNumber(string str)
{
istringstream iss(str);
double num;
iss >> num;
return num;
}