通过键盘输入100以内正整数的加、减运算式,请编写一个程序输出运算结果字符串。
输入字符串的格式为:“操作数1 运算符 操作数2”,“操作数”与“运算符”之间以一个空格隔开。
补充说明:
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"
#include"math.h"
int arithmetic(const char *input, int lInputLen, char *output)
{
int sum=0;
int operator1=0;
int operator2=0;
char temp[12]={' '};
char *ope;
int i=0;
while(*input !=' ')
{
if(*input>='0'&&*input<='9')
{
sum=sum*10+(*input++-'0');
}
// sum=sum*10+(*input++-'0');
else
return 0;
}
input++;
operator1=sum;
sum=0;
i=0;
while(*input !=' ')
{
temp[i++]=*input++;
}
input++;
temp[i]='\0';
ope=temp;
if(strlen(ope)>1)
{
*output++='0';
*output='\0';
return 0;
}
i=0;
while(*input !='\0')
{
if(*input>='0'&&*input<='9')
{
sum=sum*10+(*input++-'0');
}
else
return 0;
}
operator2=sum;
sum=0;
switch(*ope)
{
case '+':itoa(operator1+operator2,output,10);
break;
case '-':itoa(operator1-operator2,output,10);
break;
default:
*output++='0';
*output='\0';
return 0;
}
return 1;
}
void main()
{
char inputString[]="11111 - 110";
char outputString[100];
printf("运算前的字符串:\n");
printf("%s\n",inputString);
if(arithmetic(inputString,strlen(inputString),outputString)==0)
printf("输出格式有误\n");
else
{
printf("运算后的字符串:\n");
printf("%s\n",outputString);
}
getch();
}