/*题3 通过键盘输入100以内正整数的加、减运算式,请编写一个程序输出运算结果字符串。 输入字符串的格式为:“操作数1 运算符 操作数2”,“操作数”与“运算符”之间以一个空格隔开。
补充说明:
操作数为正整数,不需要考虑计算结果溢出的情况.
若输入算式格式错误,输出结果为“0”。
要求实现函数:
void arithmetic(const char * pInputStr, long lInputLen, char * pOutputStr);
【输入】
pInputStr:输入字符串
lInputLen:输入字符串长度
【输出】
pOutputStr:输出字符串,空间已经开辟好,与输入字符串等长;
【注意】
只需要完成该函数功能算法,中间不需要有任何IO的输入输出
示例
输入:4 + 7 输出:11
输入:4 - 7 输出:-3
输入:9 ++ 7 输出:0 注:格式错误
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void arithmetic(char *pInputStr1, long lInputLen, char *pOutputStr) {
char *pch = NULL;
char *cur = malloc(lInputLen + 1);
*pOutputStr = '\0';
int oprand1 =0, oprand2 = 0, count = 0;
char *operator = NULL;
strcpy(cur, pInputStr1);
pch = strtok(cur, " ");//获取第一个子字符串
while(pch != NULL) {//继续获取其它子串
if (count == 0) {
oprand1 = atoi(pch);
} else if(count == 2) {
oprand2 = atoi(pch);
} else {
operator = pch;
}
pch = strtok(NULL, " ");
count ++;
}
/* switch (operator[0]){
case '+':
oprand1 += oprand2;
sprintf(pOutputStr + strlen(pOutputStr), "%d", oprand1);
break;
case '-':
oprand1 -= oprand2;
sprintf(pOutputStr + strlen(pOutputStr), "%d", oprand1);
break;
default:
sprintf(pOutputStr + strlen(pOutputStr), "%d", 0);
printf("格式错误\n");
} */
if (strcmp(operator, "+") == 0){
oprand1 += oprand2;
sprintf(pOutputStr + strlen(pOutputStr), "%d", oprand1);
}else if (strcmp(operator, "-") == 0){
oprand1 -= oprand2;
sprintf(pOutputStr + strlen(pOutputStr), "%d", oprand1);
}else {
sprintf(pOutputStr + strlen(pOutputStr), "%d", 0);
printf("格式错误\n");
}
free(cur);
}
int main(void) {
char pInputStr[128] = {"3 + 5"};
char pOutputStr[128] = {0};
arithmetic(pInputStr, strlen(pInputStr), pOutputStr);
printf("输出:%s\n", pOutputStr);
return 0;
}