/*
* 程序功能:简单计算器,实现加减乘除平方
* 作者版本日期:2015.11.08 zhouhb OK
* 源代码:李明 《新概念C语言培训》第33集 C语言Shell命令解释器的实现
* 代码存储位置 :133 /home/zhouhb/test/calculator.c
* 整体思路:函数指针,main函数传参
*/
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
int m_debug = 0;
int (*pf)(int ,int);
char opchar_math;//打印运算符
//函数和名字对应
struct operation{
char name[8];
int (*pf)(int,int);
char opchar;
};
int add(int a,int b)
{
return a+b;
}
int sub(int a,int b)
{
return a-b;
}
int mul(int a,int b)
{
return a*b;
}
int divi(int a,int b)//div是C的函数
{
if(b<=0)
return 0;
return a/b;
}
int power(int a,int b)
{
int i = 0,num = 1;
for(i=0;i<b;i++)
{
num = num * a;
}
return num;
}
struct operation op[]={
{"add",add,'+'},
{"sub",sub,'-'},
{"mul",mul,'*'},
{"div",divi,'/'},
{"pow",power,'^'}
};
int math(int argc,char *argv[])
{
int a=0,b=0,num=0;
int result;
a = atoi(argv[1]);
b = atoi(argv[2]);
result = pf(a,b);
printf("%d %c %d = %d
",a,opchar_math,b,result);
}
//函数和函数指针对应
int command_do(int argc,char* argv[])
{
#if 0
if(strncmp(argv[0],"add",3)==0)
pf = add;
if(strncmp(argv[0],"sub",3)==0)
pf = sub;
if(strncmp(argv[0],"mul",3)==0)
pf = mul;
if(strncmp(argv[0],"divi",4)==0)
pf = divi;
if(strncmp(argv[0],"pow",3)==0)
pf = power;
#endif
int i = 0;
for(i = 0;i<sizeof(op)/sizeof(op[0]);i++)
{
if(strcmp(argv[0],op[i].name)==0)
{
pf = op[i].pf;
opchar_math = op[i].opchar;
break;
}
}
math(argc,argv);
}
//模拟main对输入进行处理
void shell_parse(char* buff)
{
int argc = 0;
char *argv[8];
int state = 0;
int i = 0;
while(*buff)
{
char c = *buff;
if(c == ' '&&state == 0)//" add 100"开始有空格
state = 0;
else if(c != ' '&& state == 0)//"add 100"解析第一个
{
argv[argc++] = buff;
state = 1;
}
else if(c == ' ' && state ==1)//"a dd 100"解析完add遇到空格
{
*buff = ' ';
state = 0;
}
else if(c != ' '&&state == 1)//"add 100"解析add中d
{
state = 1;
}
buff++;
if(*buff == '
')//传入有回车
*buff = '
';
}
argv[argc] = NULL;//避免出现乱编
if(m_debug==1)
{
printf("argc = %d
",argc);
for(i=0;i<argc;i++)
{
printf("argv[%d]:%s
",i,argv[i]);
}
}
command_do(argc,argv);
}
int main(int argc,char* argv[],char* env[])
{
int i=0;
char buff[254];
int num=0;
if(argc >1 && strlen(argv[1])>1 && strncmp(argv[1],"-d",2)==0)
m_debug = 1;
printf("input name num1 num2
");
while(1)
{
printf("NCCL#");
fgets(buff,254,stdin);//不用scanf,gets
if(m_debug)
printf("buff=%s
",buff);
shell_parse(buff);
}
#if 0
printf("argc = %d
",argc);
for(i=0;i<argc;i++)
{
printf("argv[%d]:%s
",i,argv[i]);
}
for(i=0;i<=3;i++)
printf("env[%d]:%s
",i,env[i]);
#endif
}