c++ - 提取括号外数字的代码不起作用
问题描述
我正在尝试编写一个简单的程序来提取最后一对括号之外的数字和操作数,我试图通过使用一个简单的递归函数来实现这一点,但是,我的代码没有打印任何内容。代码有什么问题?
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();
}
解决方案
问题在于错误的停止条件导致该行中的无限递归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);
}
}
推荐阅读
- mysql - sql:选择 * 和最小值,没有过滤行
- c++ - C++ 简化类/OOP 方法
- kubernetes - 并行 pod 的 subPathExpr
- javascript - 单击色板时如何更改特色图像?
- elasticsearch - 在 idex 中查找短语
- vue.js - 如何在 v-textarea 中隐藏滚动条?
- python - RNN 带或不带循环:每个输出的含义?
- python - Cisco WebEx:使用 Python 2.7 为一组新令牌生成新代码时出现问题
- php - 如何在 laravel 版本 5.0.35 中配置任何 restful api 包,如 laravel/passort 或 dingo/api(*没有作曲家)
- html - 是否有任何 CSS 代码来定位图像,如下所示但也响应屏幕尺寸?