Làm cách nào để ngăn việc in biểu thức postfix khi có lỗi?

lập trình


Nó chỉ nên in lỗi chứ không in biểu thức postfix như sau.

Nhập biểu thức trung tố: +
Lỗi: số toán hạng không hợp lệ
Nhập biểu thức trung tố: 1+
Lỗi: số toán hạng không hợp lệ
Nhập biểu thức trung tố: +1
Lỗi: số toán hạng không hợp lệ
Nhập biểu thức trung tố: 1-+4
Lỗi: số toán hạng không hợp lệ

Tôi đã thử tạo cờ lỗi để theo dõi lỗi như ai đó đã đề cập. Tuy nhiên, vấn đề vẫn tồn tại và tôi không hiểu tại sao.

Những gì tôi đã thử:

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;
}

Giải pháp 1

Đây cũng chính là câu hỏi bạn đã hỏi ngày hôm qua: Làm cách nào để ngăn việc in biểu thức postfix khi có lỗi với số toán hạng không hợp lệ?[^] – giải pháp không thay đổi qua đêm.

コメント

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