如何防止在出现错误时打印后缀表达式?


它应该只打印错误而不是后缀表达式,如下所示。

输入中缀表达式:+
错误:操作数数量无效
输入中缀表达式:1+
错误:操作数数量无效
输入中缀表达式:+1
错误:操作数数量无效
输入中缀表达式:1-+4
错误:操作数数量无效

正如有人提到的,我尝试创建一个错误标志来跟踪错误。 但是,问题仍然存在,我不明白为什么。

我尝试过的:

C++
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>

using namespace std;

const int MAX_SIZE = 100;
bool errorOccurred = false;

class Stack{
  private:
    int top;
    string stackArray[MAX_SIZE];

  public:
    Stack(){
      top = -1;
    }

    void push(string s){
      if(top >= (MAX_SIZE - 1)){
        cout << "Stack Overflow";
      }
      else{
        top++;
        stackArray[top] = s;
      }
    }

    string pop(){
      if(top < 0){
        return "";
      }
      else{
        string s = stackArray[top];
        top--;
        return s;
      }
    }

    string peek(){
      if(top < 0){
        cout << "Stack is empty";
        return "";
      }
      else{
        string s= stackArray[top];
        return s;
      }
    }

    bool isEmpty() {
      return(top < 0);
    }
};

bool isNumber(string s){
  if(s >= "0" && s <= "9"){
    return true;
  }
  else{
    return false;
  }
}

bool isOperator(string s){
  if(s == "+" || s == "-" || s == "*" || s == "/" || s == "^"){
    return true;
  }
  else{
    return false;
  }
}

bool isValidCharacter(string s){
  if(isNumber(s) || isOperator(s)){
    return true;
  }
  else if(s == "(" || s == ")"){
    return true;
  }
  else if(s == "{" || s == "}"){
    return true;
  }
  else if(s == "[" || s == "]"){
    return true;
  }
  else{
    return false;
  }
}

int precedence(string op){
  if(op == "^"){
    return 3;
  }
  else if(op == "*" || op == "/"){
    return 2;
  }
  else if(op == "+" || op == "-"){
    return 1;
  }
  else{
    return -1;
  }
}

bool isMatchingPair(string s1, string s2){
  if(s1 == "(" && s2 == ")"){
    return true;
  }
  else if(s1 == "{" && s2 == "}"){
    return true;
  }
  else if(s1 == "[" && s2 == "]"){
    return true;
  }
  else{
    return false;
  }
}

bool areParenthesesBalanced(string exp){
  Stack s;
  for(int i = 0; i < exp.size(); i++){
    if(exp[i] == '(' || exp[i] == '{' || exp[i] == '['){
      s.push(string(1, exp[i]));
    }
    if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']'){
      if(s.isEmpty() || !isMatchingPair(s.pop(), string(1, exp[i]))){
        return false;
      }
    }
  }
  return s.isEmpty();
}

string to_postfix(string infix){
  Stack s;
  string postfix = "";
  if(!areParenthesesBalanced(infix)) {
    cout << "Error: Invalid parentheses" << endl;
    errorOccurred = true;
    return "";
  }
  errorOccurred = false; // Reset error flag
  for (int i = 0; i < infix.size(); i++) {
    string infixString(1, infix[i]); 
    if (infix[i] == ' '){
      cout << "Error: Invalid number of operators" << endl;
      errorOccurred = true;
      return "";
    }
    if (isValidCharacter(infixString)){
      if (isNumber(infixString)) {
        postfix += infixString;
      }
      else if (infixString == "(" || infixString == "[" || infixString == "{") {
        s.push(infixString);
      }
      else if (infixString == ")" || infixString == "]" || infixString == "}") {
        while (!s.isEmpty() && s.peek() != "(" && s.peek() != "[" && s.peek() != "{") {
          postfix += s.pop();
        }
        if (s.isEmpty()) {
          cout << "Error: Invalid parentheses" << endl;
          errorOccurred = true;
          return "";
        }
        else {
          s.pop();
        }
      }
      else {
        while (!s.isEmpty() && precedence(infixString) <= precedence(s.peek())) {
          postfix += s.pop();
        }
        s.push(infixString);
      }
    }
    else{
      cout << "Invalid character '" << infix[i] << "' in the expression" << endl;
      errorOccurred = true;
      return "";
    }
  }
  while (!s.isEmpty()) {
    postfix += s.pop();
  }
  return postfix;
}

void print_postfix(string postfix){
  if(!errorOccurred){
    cout << "Postfix expression: ";
    for(int i = 0; i < postfix.size(); i++){
      cout << postfix[i] << " ";
    }
    cout << endl;
  }
}

double evaluatePostfix(string postfix){
  Stack s;
  for(int i = 0; i < postfix.size(); i++){
    string postfixString(1, postfix[i]);
    if(isOperator(postfixString)){
      if(s.isEmpty()){
        cout << "Error: Invalid number of operands";
        errorOccurred = true;
        return 0;
      }
      int op1 = stoi(s.pop());
      if(s.isEmpty()){
        cout << "Error: Invalid number of operands";
        errorOccurred = true;
        return 0;
      }
      int op2 = stoi(s.pop());
      double result = 0.0;

      switch(postfix[i]){
        case '+':
          result = op2 + op1;
          break;
        case '-':
          result = op2 - op1;
          break;
        case '*':
          result = op2 * op1;
          break;
        case '/':
          if(op1 == 0){
            cout << "Error: Division by zero" << endl;
            errorOccurred = true;
          }
          result = (double)op2 / op1;
          break;
        case '^':
          result = pow(op2, op1);
          break;
        case '%':
          result = fmod(op2, op1);
          break;
        default:
          cout << "Error: Invalid operator" << endl;
          errorOccurred = true;
      }
      s.push(to_string(result)); 
    }
    else{
      s.push(postfixString);
    }
  }
  if(!s.isEmpty()) {
    string resultString = s.pop();
    if(!resultString.empty() && isNumber(resultString)){
      return stod(resultString);
    }
  }
  return 0;
}

int main() {
  string infixExpression;
  cout << "Enter an infix expression: ";
  getline(cin, infixExpression);

  string postfixExp = to_postfix(infixExpression);
  
  print_postfix(postfixExp);

  double result = evaluatePostfix(postfixExp);
    if(result != 0.0){
      cout << "Result: " << fixed << setprecision(3) << result << endl;
    }
  
  return 0;
}

解决方案1

这和你昨天问的问题是一样的: 当出现操作数数量无效的错误时,如何防止打印后缀表达式?[^] – 解决方案不会在一夜之间发生变化。

コメント

タイトルとURLをコピーしました