首页 > 解决方案 > 提取括号外数字的代码不起作用

问题描述

我正在尝试编写一个简单的程序来提取最后一对括号之外的数字和操作数,我试图通过使用一个简单的递归函数来实现这一点,但是,我的代码没有打印任何内容。代码有什么问题?

class Puller{
    private:
    std::vector<std::string> container;
    std::string cache;
    public:
    void sep(std::string x, int y){
        if(x[y] != '('){
            cache.push_back(x[y]);
            sep(x,y + 1);
        }
        else if(x[y] == '('){
            container.push_back(cache);
            cache.clear();
            sep(x,y + 1);
        }
        else if(x[y] == ')'){
            cache.clear();
            sep(x,y + 1);
        }
        else if(x[y] == NULL){
            container.push_back(cache);
        }
    }
    void show(){
        for(auto i : container){
            std::cout<<"Radicals: "<<i<<'\n';
        }
    }
};
int main(int argc, char** argv){
    const std::string str = "100+(2*3+4)*2";
    Puller larry;
    larry.sep(str,0);
    larry.show();
}

标签: c++

解决方案


问题在于错误的停止条件导致该行中的无限递归if(x[y] != '('){。你只需要把那个条件放在最后,或者你可以忽略它。

   void sep(std::string x, int y){ 
        if(x[y] == '('){
            container.push_back(cache);
            cache.clear();
            sep(x,y + 1);
        }
        else if(x[y] == ')'){
            cache.clear();
            sep(x,y + 1);
        }
        else if(x[y] == NULL) {
            container.push_back(cache);
        }
        else if(x[y] != '('){ // if can be omitted
            cache.push_back(x[y]);
            sep(x,y + 1);
        }
    }

推荐阅读