在文件中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:
23+45=68
20+(13-10)=23
(-4-12)+(22*5)=4
54/(3+(9-3))=6
要实现这个程序,可以按照以下步骤进行:
这是一个基本的实现思路,下面是一个可能的C++代码示例:
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
// 函数声明
string prefixToInfix(string prefixExpr);
int evaluateInfix(string infixExpr);
bool isOperator(char c);
int getOperatorPriority(char c);
int performOperation(int operand1, int operand2, char op);
int main() {
string inputFilePath = "input.txt";
string outputFilePath = "output.txt";
ifstream inputFile(inputFilePath);
ofstream outputFile(outputFilePath);
if (!inputFile) {
cout << "无法打开输入文件!" << endl;
return 1;
}
if (!outputFile) {
cout << "无法打开输出文件!" << endl;
return 1;
}
string prefixExpr;
while (getline(inputFile, prefixExpr)) {
string infixExpr = prefixToInfix(prefixExpr);
int result = evaluateInfix(infixExpr);
outputFile << result << endl;
}
inputFile.close();
outputFile.close();
return 0;
}
string prefixToInfix(string prefixExpr) {
stack<string> exprStack;
int len = prefixExpr.length();
for (int i = len - 1; i >= 0; i--) {
char ch = prefixExpr[i];
if (isOperator(ch)) {
string operand1 = exprStack.top();
exprStack.pop();
string operand2 = exprStack.top();
exprStack.pop();
string temp = "(" + operand1 + ch + operand2 + ")";
exprStack.push(temp);
} else {
exprStack.push(string(1, ch));
}
}
return exprStack.top();
}
int evaluateInfix(string infixExpr) {
stack<int> operandStack;
stack<char> operatorStack;
int len = infixExpr.length();
for (int i = 0; i < len; i++) {
char ch = infixExpr[i];
if (isdigit(ch)) {
operandStack.push(ch - '0');
} else if (isOperator(ch)) {
while (!operatorStack.empty() && getOperatorPriority(operatorStack.top()) >= getOperatorPriority(ch)) {
int operand2 = operandStack.top();
operandStack.pop();
int operand1 = operandStack.top();
operandStack.pop();
char op = operatorStack.top();
operatorStack.pop();
int result = performOperation(operand1, operand2, op);
operandStack.push(result);
}
operatorStack.push(ch);
}
}
while (!operatorStack.empty()) {
int operand2 = operandStack.top();
operandStack.pop();
int operand1 = operandStack.top();
operandStack.pop();
char op = operatorStack.top();
operatorStack.pop();
int result = performOperation(operand1, operand2, op);
operandStack.push(result);
}
return operandStack.top();
}
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int getOperatorPriority(char c) {
if (c == '+' || c == '-') {
return 1;
} else if (c == '*' || c == '/') {
return 2;
}
return 0;
}
int performOperation(int operand1, int operand2, char op) {
switch (op) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
default:
return 0;
}
}
上述示例代码是一个基本的实现,可以根据需要对其进行修改和优化。可以根据具体的输入文件和输出文件路径进行调整,并进行错误处理和边界情况的考虑。另外,实际应用中可能会遇到更复杂的操作符和表达式,需要进一步进行扩展和优化。
将值写入 ?那你这图