检查前缀表达式检查语法合法性的代码c++,要求有当输入的不是前缀表达式或除数为0时是要显示“错误
时间: 2024-04-05 20:33:33 浏览: 48
biaodashi.rar_将 前缀 转换成 中缀
5星 · 资源好评率100%
当输入的不是前缀表达式或除数为0时显示错误的代码示例(C++)如下所示:
```cpp
#include <iostream>
#include <stack>
#include <sstream>
bool isOperator(const std::string& token) {
return (token == "+" || token == "-" || token == "*" || token == "/");
}
bool isNumber(const std::string& token) {
std::istringstream iss(token);
double num;
iss >> num;
return !iss.fail();
}
bool isValidPrefixExpression(const std::string& expr) {
std::istringstream iss(expr);
std::stack<std::string> stack;
std::string token;
while (iss >> token) {
if (isOperator(token)) {
if (stack.size() < 2) {
return false; // Invalid expression: not enough operands
}
stack.pop();
}
else if (isNumber(token)) {
stack.push(token);
}
else {
return false; // Invalid expression: invalid token
}
}
return (stack.size() == 1);
}
double evaluatePrefixExpression(const std::string& expr) {
std::istringstream iss(expr);
std::stack<double> stack;
std::string token;
while (iss >> token) {
if (isOperator(token)) {
if (stack.size() < 2) {
throw std::runtime_error("Invalid expression: not enough operands");
}
double operand2 = stack.top();
stack.pop();
double operand1 = stack.top();
stack.pop();
if (token == "+")
stack.push(operand1 + operand2);
else if (token == "-")
stack.push(operand1 - operand2);
else if (token == "*")
stack.push(operand1 * operand2);
else if (token == "/") {
if (operand2 == 0) {
throw std::runtime_error("Error: Division by zero");
}
stack.push(operand1 / operand2);
}
}
else if (isNumber(token)) {
std::istringstream issNum(token);
double num;
issNum >> num;
stack.push(num);
}
}
if (stack.size() == 1) {
return stack.top();
}
else {
throw std::runtime_error("Invalid expression: too many operands");
}
}
int main() {
std::string expr;
std::cout << "Enter a prefix expression: ";
std::getline(std::cin, expr);
if (isValidPrefixExpression(expr)) {
try {
double result = evaluatePrefixExpression(expr);
std::cout << "Result: " << result << std::endl;
}
catch (const std::runtime_error& error) {
std::cout << "Error: " << error.what() << std::endl;
}
}
else {
std::cout << "Invalid prefix expression" << std::endl;
}
return 0;
}
```
这段代码可以检查输入是否为前缀表达式,并计算其结果。如果输入的不是前缀表达式或除数为0,则会显示相应的错误信息。
阅读全文