#include <stdio.h>
#include <setjmp.h>
#include <string.h>
#define DEBUG
jmp_buf jb_env;
#define CMD_ADD 1
#define CMD_SUB 2
#define CMD_MUL 3
#define CMD_DIV 4
#define GO_TO_START 0
#define ERR_DIV_ZERO (11)
#define ERR_CMD (12)
double div(double lvar,double rvar);
void analysis_expr(char * str_exp);
#define LINE_MAX_SIZE 100
double lvar;
double rvar;
char optr;
char str_exp[LINE_MAX_SIZE];
int
main()
{
int setjmp_result = 0;
switch((setjmp_result = setjmp(jb_env)))
{
case ERR_DIV_ZERO:
printf("Divided by Zero!\n");
break;
case ERR_CMD:
printf("Command error!\n");
break;
}
printf("Enter<example:ADD 1 2>:");
fgets(str_exp,LINE_MAX_SIZE,stdin);
analysis_expr(str_exp);
switch(optr)
{
case CMD_ADD:
printf("%lf + %lf = %lf\n",lvar,rvar,lvar+rvar);
break;
case CMD_SUB:
printf("%lf - %lf = %lf\n",lvar,rvar,lvar-rvar);
break;
case CMD_MUL:
printf("%lf * %lf = %lf\n",lvar,rvar,lvar*rvar);
break;
case CMD_DIV:
printf("%lf / %lf = %lf\n",lvar,rvar,div(lvar,rvar));
break;
}
longjmp(jb_env,GO_TO_START);
}
void
analysis_expr(char * str_exp)
{
char * ptr = strtok(str_exp," ");
//解析符号;
if(!strcasecmp(ptr,"add"))
optr = CMD_ADD;
else if(!strcasecmp(ptr,"sub"))
optr = CMD_SUB;
else if(!strcasecmp(ptr,"mul"))
optr = CMD_MUL;
else if(!strcasecmp(ptr,"div"))
optr = CMD_DIV;
else{
longjmp(jb_env,ERR_CMD);
}
ptr = strtok(NULL," ");
char * endptr = NULL;
lvar = strtol(ptr,&endptr,10);
if((*endptr)!=0)
{
longjmp(jb_env,ERR_CMD);
}
ptr = strtok(NULL," ");
rvar = strtol(ptr,&endptr,10);
if((*endptr!=0)&&(*endptr!='\n'))
{
printf("endptr:%d.",*endptr);
longjmp(jb_env,ERR_CMD);
}
return ;
}
double
div(double lvar,double rvar)
{
if(rvar < 0.5 && rvar > -0.5)
longjmp(jb_env,ERR_DIV_ZERO);
return (lvar/rvar);
}
关于setjmp longjmp的使用
最新推荐文章于 2021-04-14 14:16:06 发布