为什么这个 C++ 代码会产生奇怪的字符?

问题描述

我想在 C++ 中简化代数表达式。我从简单的事情开始:从包含 +- 运算符的代数表达式中删除括号。例如,a-(b-c) 应简化为 a-b+cThis 链接给出了这个问题的答案。这是源代码

#include <iostream>
#include <string.h>
#include <stack>

using namespace std; 
  
// Function to simplify the string 
char* simplify(string str) 
{ 
    int len = str.length(); 
  
    // resultant string of max length equal 
    // to length of input string 
    char* res = new char(len); 
    int index = 0,i = 0; 
  
    // create empty stack 
    stack<int> s; 
    s.push(0); 
  
    while (i < len) { 
        if (str[i] == '+') { 
  
            // If top is 1,flip the operator 
            if (s.top() == 1) 
                res[index++] = '-'; 
  
            // If top is 0,append the same operator 
            if (s.top() == 0) 
                res[index++] = '+'; 
  
        } else if (str[i] == '-') { 
            if (s.top() == 1) 
                res[index++] = '+'; 
            else if (s.top() == 0) 
                res[index++] = '-'; 
        } else if (str[i] == '(' && i > 0) { 
            if (str[i - 1] == '-') { 
  
                // x is opposite to the top of stack 
                int x = (s.top() == 1) ? 0 : 1; 
                s.push(x); 
            } 
  
            // push value equal to top of the stack 
            else if (str[i - 1] == '+') 
                s.push(s.top()); 
        } 
  
        // If closing parentheses pop the stack once 
        else if (str[i] == ')') 
            s.pop(); 
  
        // copy the character to the result 
        else
            res[index++] = str[i]; 
        i++; 
    } 
    return res; 
} 

我在 a-(b-c-(d+e))-f 上测试了该函数,结果为 a-b+c+d+e-fÿï┌。为什么会产生奇怪的字符?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)