#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include "mystack.h"
#include "myqueue.h"
#define DEBUG 0
#define MAX_LENGTH_TXT 500
typedef enum {
ERR_NONE = 0,
ERR_IO,
ERR_STACK,
ERR_QUEUE
} errNum;
typedef struct {
errNum error;
int line;
} myError;
int getExpr(char expr[]);
myError processQueue(char expr[], int len_txt);
double calcQueue();
char* zeroRid(double num);
int main() {
char expr[MAX_LENGTH_TXT];
int len_txt = 0;
myError err;
double res;
while (1) {
stackClean();
queueClean();
printf("please input a expression (Supported operators '+ - * / ( )' and Bracket nesting) or 'q' to exit\n> ");
len_txt = getExpr(expr); // 获取输入
if (len_txt == -1) {
break;
} else if (len_txt == 0) {
continue;
}
#if (DEBUG == 1)
printf("> %s | Length: %d\n", expr, len_txt);
#endif
err = processQueue(expr, len_txt); // 处理表达式
if (err.error == ERR_IO) {
printf("[ERROR_IO]: (Line: %d)Please check the input carefully and try again later\n", err.line);
continue;
} else if (err.error == ERR_QUEUE) {
printf("[ERROR_QUEUE]: (Line: %d)Queue full, input too long please try again\n", err.line);
continue;
} else if (err.error == ERR_STACK) {
printf("[ERROR_STACK]: (Line: %d)Stack full, input too long please try again\n", err.line);
continue;
}
#if (DEBUG == 1)
printf("> ");
queuePrint();
#endif
res = calcQueue(); // 计算结果
printf("= %s\n", zeroRid(res));
}
return 0;
}
/* 获取运算符优先级 */
uint8_t priority(char symbol) {
switch (symbol) {
case '+':
case '-': return 1;
case '*':
case '/': return 2;
case '(': return 3;
}
return 0;
}
/* 从标准输入中读入一行表达式
* 返回读入的字符串长度
* -1 表示输入为退出标记或栈满退出
*/
int getExpr(char expr[]) {
char ch;
int len_txt = 0;
while (1) {
ch = getchar();
if (ch == 'q') { // 输入q, 直接退出
len_txt = -1;
break;
}
if ((ch >= '0' && ch <= '9') || ch == '.' || ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '(' || ch == ')') {
/* 输入过滤 */
expr[len_txt++] = ch;
if (len_txt >= MAX_LENGTH_TXT) {
len_txt = -1;
break; // 输入溢出
}
} else if (ch == '\n') {
expr[len_txt] = '\0';
break;
}
}
return len_txt;
}
/* 处理中序表达式,以逆波兰形式存入队列
* 没有错误,返回0
*/
myError processQueue(char expr[], i
四则运算计算机C++项目练习
最新推荐文章于 2022-10-10 21:31:58 发布