Esempio n. 1
0
static int opr_handler(struct calc *calc)
{
	assert(calc != NULL);
	char c = *calc->cur;
	opr_advance(calc);
	/* 如果操作符栈是空栈的话就压栈 */
	if (STACK_IS_EMPTY(calc->opr)) {
		OPR_PUSH(c);
		return 0;
	}

	/* 如果操作符栈非空, 且该操作符优先级高于栈顶运算符就压栈 */
	char top_c = 0;
	if (OPR_TOP(top_c) < 0) {
		fprintf(stderr, "Error: opr top failed.\n");
		return -1;
	}
	
	while(1) {
		if (opr2level(c) > opr2level(top_c) || STACK_IS_EMPTY(calc->opr)) {
			OPR_PUSH(c);
			return 0;
		}
		if (do_operate(calc) < 0) {
			fprintf(stderr, "Error: do operate failed.\n");
			return -1;
		}
		if ( !STACK_IS_EMPTY(calc->opr) && OPR_TOP(top_c) < 0) {
			fprintf(stderr, "Error: while opr top failed.\n");
			return -1;
		}
	}
	return 0;
}
Esempio n. 2
0
static int opr_handle(struct calc_info *info)
{
	assert(info != NULL);
	
	char c = *info->cur;

	if (info->flag == NUM) {
		info->flag = OPR;
	} else {
		switch (c) {
			case '+':
				goto out;
				break;
			case '-':
				//FIXME 负号的处理
				{
				  num_t zero = 0;
				  NUM_PUSH(zero);
				  OPR_PUSH(c);
				  goto out;	
				}
				break;
			default: 
				fprintf(stderr, "免费版不支持多个运算符\n");
				break;
		}
	}

	//1. 入栈的两种情况: a) 空栈  b)运算符优先级高于栈顶运算符
	
	if (OPR_IS_EMPTY) {
		OPR_PUSH(c);
	} else {
		char top_c;
		while (1) {
			//a 空栈
			if (OPR_TOP(top_c) < 0) {
				OPR_PUSH(c);
				break;
			}
			//b 优先级高于栈顶
			if (opr2level(c) > opr2level(top_c)) {
				OPR_PUSH(c);
				break;
			} else {
				if (do_stack(info) < 0) {
					fprintf(stderr,"do_stack failed\n");
					goto err_do_stack;
				}
			}
		}
	}
out:	
	return 0;
err_do_stack:
	return -1;
}
Esempio n. 3
0
static int opr_handler(struct calc *calc)
{
	assert(calc != NULL);
	char c = *calc->cur;
	int zero = 0;
	if (calc->pre_flag == F_NUM) {
		calc->pre_flag = F_OPR;
	} else if (calc->pre_flag == F_OPR) {
		if (c == '-') {
			NUM_PUSH(zero);
			OPR_PUSH(c);
			calc->pre_flag = F_OPR;
			return 0;
		} else if (c == '+') {
			return 0;
		}
	} else {
		fprintf(stderr, "unknow character\n");
		return -2;
	}

	/* 如果操作符栈是空栈的话就压栈 */
	if (STACK_IS_EMPTY(calc->opr)) {
		OPR_PUSH(c);
		return 0;
	}

	/* 如果操作符栈非空, 且该操作符优先级高于栈顶运算符就压栈 */
	char top_c = 0;
	if (OPR_TOP(top_c) < 0) {
		fprintf(stderr, "Error: opr top failed.\n");
		return -1;
	}
	
	while(1) {
		if (opr2level(c) > opr2level(top_c) || STACK_IS_EMPTY(calc->opr)) {
			OPR_PUSH(c);
			return 0;
		}
		if (do_operate(calc) < 0) {
			fprintf(stderr, "Error: do operate failed.\n");
			return -1;
		}
		if ( !STACK_IS_EMPTY(calc->opr) && OPR_TOP(top_c) < 0) {
			fprintf(stderr, "Error: while opr top failed.\n");
			return -1;
		}
	}
	return 0;
}