[用例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*來傳遞參數。