功能描述
自定义运算函数如:add(加),sub(减),mult(乘),div(除以),neg(取反),doubleMe(平方)计算嵌套函数调用式如:
add(20,sub(13,10))的值23。
运行示例
在文件中question.txt逐行存储:
add(23,45)
add(-20,sub(13,10))
add(sub(neg(4),12), muti(doubleMe(2),5))
div(54,add(3,sub(9,3))
将值写入文件answer.txt:
add(23,45)=68
add(20,sub(13,10)) = 23
add(sub(neg(4),12), muti(doubleMe(2),5)) = 4
div(54,add(3,sub(9,3)) = 6
这是题目,
下面是我的代码
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
#include <cmath>
using namespace std;
string mLine;
stack<int> a; //创建一个栈存放数字以及计算结果
void test01(string& s) //前缀表达式的计算
{
stack<char>b; //创建一个栈存放符号
cout << "begin" << endl;
int i = s.length() - 1;
for (i = s.length() - 1; i >= 0; i--)
{
if (isdigit(s[i]!=0))
{
int num = 0, j = 0, mum = 1;
while (i >0 && isdigit(s[i])!=0) { //当是数字时一直循环直到下一位不是数字为止再将数字压入数字栈中
num += ((s[i] - '0') * mum);
i++; mum *= 10;
}
i--;
a.push(num);//将数字压入栈中
}
else if (s[i] == ')'||s[i]=='(') b.push(s[i]);
else if (s[i] == ' ' || s[i] == ',') continue;
else if (s[i] == '^'||s[i]=='`')
{
b.pop();
b.pop(); //删除栈顶的左右括号
int x1 = a.top();
a.pop(); // 取出一个数字并从栈中删去
if (s[i] == '~') a.push(-(s[i] - '0'));
else if (s[i] == '^') a.push((s[i] - '0')*(s[i] - '0'));
}
else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')
{
b.pop(); //删去左括号
int t1 = a.top();
a.pop();//出栈
int t2 = a.top();
a.pop();//出栈 ,删除 //取出两个数字
switch (s[i])
{
case'+':a.push(t1 + t2); break;
case'-':a.push(t1 - t2); break;
case'*':a.push(t1 * t2); break;
case'/':a.push(t1 / t2); break;
//分情况进行计算,然后将计算结果压入栈中进行下一轮循环
}
}
}//栈顶元素即为计算结果
cout << a.top() << endl;
cout << b.top() << endl;
}
void zhuanhuan(string& line) //将字符串中的英文运算符单词该为对应的符号
{
int i = 0;
while( i <(line.length()))
{
if (line[i] == 'a' )
{
mLine += '+';
i += 2;
}
else if (line[i] == 's')
{
mLine += '-';
i += 2;
}
else if (line[i] == 'm')
{
mLine += '*';
i += 3;
}
else if (line[i] == 'd' && line[i + 1] == 'i')
{
mLine += '/';
i += 2;
}
else if (line[i] == 'n' )
{
mLine += '~'; //自定义取反符号为~
i += 2;
}
else if (line[i] == 'd'&& line[i + 1] == 'o' )
{
mLine += '^';
i += 7;
}
else {
mLine += line[i];
}
cout << mLine << endl;
i++;
}
cout << "over" << endl;
}
int main() {
ifstream inputFile("question.txt");
ofstream outputFile("answer.txt");
if (!inputFile || !outputFile) {
cout << "Failed to open the file!" << endl;
return 1;
}
string line1;
while (getline(inputFile, line1))
{
zhuanhuan(line1); //将line中英文单词转换为运算符填入字符串mLine中
test01(mLine);
int result = a.top();
outputFile << line1 << "=" << result << endl;
mLine =" " ; //每一次循环都初始化字符串mLine
}
inputFile.close(); //关闭文件
outputFile.close();
return 0;
}
下面图片是运行之后出现的问题,我搜的资料说是因为内存越界,比如“数组越界”、“释放已经释放掉的内存”、“共享内存引发的问题”、“释放野指针的问题”等,但是我实在不知道哪里出问题了
你调试下,stack为空,你却继续尝试出栈
你注意,要调试你的代码,不要调试到库函数内部去,你可以打开调用堆栈窗格,往下找到你的调用的地方