[用例1] 23+5- 结果是0
[用例2] 235*+ 结果是17
[用例3] 235*+2- 结果是-15
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stack>
using namespace std;
//字符转整数
int ch2int(char ch)
{
int value;
if (ch >= '0'&&ch <= '9')
value = ch - '0';
else if (ch >= 'a'&&ch <= 'f')
value = ch - 'a' + 10;
else if (ch >= 'A'&&ch <= 'F')
value = ch - 'A' + 10;
return value;
}
//题目要求,本函数的参数是const char*
int ComputeAfterOrder(const char *str)
{
stack<int> stk;
int i = 0;
int data[2];
int result;
while (str[i] != '\0')//字符串结束标志
{
//数字
if((str[i]>='0'&&str[i]<='9')|| (str[i] >= 'a'&&str[i] <= 'f') || (str[i] >= 'A'&&str[i] <= 'F'))
stk.push(ch2int(str[i]));
//运算符
else
{
data[0] = stk.top();
stk.pop();
data[1] = stk.top();
stk.pop();
if (str[i] == '+')
stk.push(data[0] + data[1]);
if (str[i] == '-')
stk.push(data[0] - data[1]);
if (str[i] == '*')
stk.push(data[0] * data[1]);
}
i++;
}
result = stk.top();
stk.pop();
return result;
}
int main()
{
string str;
//循环读取
do{
cin >> str;
if(str[0] == EOF)
break;
cout << ComputeAfterOrder(str.c_str()) << endl;
} while (1);
return 0;
}
最初我编程在读取字符串时犯错了,如下:
char *str;
scanf("%s",str);
因为str指针没有指向有效的空间。必须用char str[100]来定义分配一个足够大的数组,或者用char *str=malloc(sizeof(int)*100)动态分配空间。
更好的办法是用string str; 调用默认构造函数分配了str的空间,使用str.c_str()转换为char*来传递参数。