/*
三、题目描述(50分):
通过键盘输入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 <iostream>
#include <string>
using namespace std;
#define N 10
void arithmetic(const char *pInputStr, long lInputLen, char *pOutputStr)
{
char *pInput = const_cast<char *>(pInputStr);
char ch;
int index1 = 0;
int index2 = 0;
int index3 = 0;
char op1[N];
char op[N];
char op2[N];
//判断输入内容是否为数字,空格及运算符.
int cnt = 0;
for(int i = 0; i < lInputLen; i++)
{
ch = pInput[i];
if(!isdigit(ch) && ch != ' ' && ch != '+' && ch != '-')
return;
}
for(int j = 0; j < lInputLen; j++)
{
ch = pInput[j];
if(ch == ' ')
{
cnt++;
if(cnt > 2)
{
cout << "too much space.";
return;
}
continue;
}
if(cnt == 0) //操作数op1.
op1[index1++] = ch;//strcat(op1,ch);
else if(cnt == 1) //操作符.
{
//或者if(pInput.rfind(' ') - pInput.find(' ') != 1)return;//格式错误.
op[index2++] = pInput[j];
if(index2 > 1)//判断类似++的情况.
{
cout << "格式错误!";
return;
}
}
else if(cnt == 2) //操作数op2.
{
op2[index3++] = pInput[j];
}
}
op1[index1] = op[index2] = op2[index3] = '\0';
cout << "op1:" << op1 << endl;
cout << "op:" << op << endl;
cout << "op2:" << op2 << endl;
int iop1 = atoi(op1);
int iop2 = atoi(op2);
int temp = 0;
if(op[0] == '+')
temp = iop1 + iop2;
else if(op[0] == '-')
temp = iop1 - iop2;
cout << temp << endl;
if(temp < 0)
{
pOutputStr[0] = '-';
itoa(-temp,pOutputStr+1,10);
}
else
itoa(temp,pOutputStr,10);
cout << "pOutputStr:" << pOutputStr << endl;
}
int main()
{
char *pch1 = "4 + 7";
int len1 = strlen(pch1);
char result1[N];
arithmetic(pch1,len1,result1);
char *pch2 = "4 - 7";
int len2 = strlen(pch2);
char result2[N];
arithmetic(pch2,len2,result2);
char *pch3 = "4 ++ 7";
int len3 = strlen(pch3);
char result3[N];
arithmetic(pch3,len3,result3);
return 0;
}