- 主干程序
- 初级版本
- 进阶版本
- 版本进化
主干程序
- 输入程序
- 解析程序
/*解析字符串 有空格把空格分开
比如输入:add 1 2
解析后:add12*/
void do_parse(char *buf)
{int state = 0;int i = 0;int argc = 0;char *argv[8] = {0};for (i = 0; buf[i]; i++){if (state == 0 && !isspace(buf[i])){state = 1;argv[argc++] = buf + i;}else if(isspace (buf[i])){state = 0;buf[i] = 0;}}argv[argc] = NULL;/*核心算法*/do_math(argc, argv);
}int main()
{char buf[1000] = {0};while (1){printf(">");scanf("%[^\n]%*c", buf);//输入if (strcmp(buf, "exit") == 0)//如果输入了"exit"就结束break;elsedo_parse(&buf);//解析程序}
}
初级版本
void do_math(char * argc, char *argv[])
{if (strcmp(argv[0], "add") == 0){int a = atoi(argv[1]);//字符串转a整形int b = atoi(argv[2]);//字符串转b整形printf("%s + %s = %d\n", argv[1], argv[2], add(a, b));//打印加法结果a+b}else if (strcmp(argv[0], "sub") == 0){int a = atoi(argv[1]);int b = atoi(argv[2]);printf("%s - %s = %d\n", argv[1], argv[2], sub(a, b));}
}
进阶版本
int add(int a, int b)
{return a + b;
}
int sub(int a, int b)
{return a - b;
}
int(*pf)(int a, int b) = NULL;
void do_math(char * argc, char *argv[])
{if (strcmp(argv[0], "add") == 0){pf = add;}if (strcmp(argv[0], "sub") == 0){pf = sub;}int a = atoi(argv[1]);int b = atoi(argv[2]);printf("%s + %s = %d\n", argv[1], argv[2], pf(a, b));
}
#include<stdio.h>
#include<stdlib.h>float add(float a, float b)
{return a + b;
}
float sub(float a, float b)
{return a - b;
}
float mul(float a, float b)
{return a * b;
}
float div(float a, float b)
{return a / b;
}int main(void)
{float(*operate[])(float, float) = { add,sub,mul,div };float number_a, number_b;float result;int oprate;printf("input the operator!1 +,2 -,3 *,4 /\n");scanf("%d", &oprate);printf("Input the number_a:");scanf("%f", &number_a);printf("Input the number_b:");scanf("%f", &number_b);printf("the result is %.3f\n",result = operate[oprate - 1](number_a, number_b));system("pause");return 0;
}
这两句关键程序
float(*operate[])(float, float) = { add,sub,mul,div };
result = operate[oprate - 1](number_a, number_b)