中缀转后缀(Infix To Postfix)C++程序无输出,无法进入循环求助
问题分析与修复方案
首先得揪出最致命的问题——函数结构错误:你的infixtopostfix函数在for循环结束后直接闭合了大括号,导致后面的while(!s.empty())和输出循环完全脱离了函数,变成了全局作用域下的非法代码。这不仅违反语法规则,还直接让函数逻辑提前终止,自然看不到后续的输出和循环内的hello打印。
接下来咱们一步步梳理所有问题并修复:
1. 修复函数核心结构
把脱离函数的代码移回infixtopostfix内部,确保逻辑完整:
void infixtopostfix(char str[m]){ char out[m]; cout<<m<<endl; stack <char> s; int k = 0; // 去掉static,每次调用重置为0,避免多次调用时的数组覆盖 // 遍历到字符串结束,而非固定m次,避免处理空字符 for(int i=0; str[i] != '\0'; i++) { cout<<"hello "; // 加空格方便观察循环执行次数 if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z')){ out[k]=str[i]; k++; } else if (str[i]=='(') { s.push(str[i]); } else if (str[i]==')'){ // 加栈非空判断,防止空栈访问崩溃 while(!s.empty() && s.top()!='('){ out[k]=s.top(); s.pop(); k++; } if(!s.empty()) s.pop(); // 确保栈不为空时再弹出左括号 } else { int curr_prio = isitoperator(str[i]); if(curr_prio != 0){ // 确认当前字符是运算符 // 栈非空、栈顶不是左括号、且栈顶优先级>=当前运算符时弹出 while(!s.empty() && s.top() != '(' && isitoperator(s.top()) >= curr_prio){ out[k]=s.top(); s.pop(); k++; } } s.push(str[i]); } } // 弹出栈中剩余的运算符 while(!s.empty()){ out[k]=s.top(); s.pop(); k++; } out[k] = '\0'; // 添加字符串终止符,避免输出乱码 cout<<endl<<"Postfix Result: "; for(int j=0;j<k;j++) cout<<out[j]; cout<<endl; }
2. 修复运算符判断函数
原函数存在两个问题:拼写错误(operattor多了一个t)、没有处理非运算符和输入中的^,会返回随机值导致逻辑混乱,补充后如下:
int isitoperator(char c) { if(c=='+'||c=='-') return 1; if(c=='*' || c=='/') return 2; if(c=='^') return 3; // 幂运算优先级高于乘除 if(c=='('||c==')') return 0; // 括号单独处理,不参与优先级比较 return 0; // 非运算符返回0 }
3. 其他细节优化
- 循环条件修正:将固定遍历m次改为遍历到字符串结束,避免处理无效的空字符。
- 栈安全访问:所有访问
s.top()的地方都先判断栈是否为空,防止程序崩溃。 - 字符串终止符:在输出数组末尾添加
'\0',避免输出乱码。
修复后的完整代码
#include <bits/stdc++.h> #define m 21 using namespace std; int isitoperator(char c) // 修正拼写错误 { if(c=='+'||c=='-') return 1; if(c=='*' || c=='/') return 2; if(c=='^') return 3; if(c=='('||c==')') return 0; return 0; } void infixtopostfix(char str[m]){ char out[m]; cout<<m<<endl; stack <char> s; int k = 0; for(int i=0; str[i] != '\0'; i++) { cout<<"hello "; if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z')){ out[k]=str[i]; k++; } else if (str[i]=='(') { s.push(str[i]); } else if (str[i]==')'){ while(!s.empty() && s.top()!='('){ out[k]=s.top(); s.pop(); k++; } if(!s.empty()) { s.pop(); } } else { int curr_prio = isitoperator(str[i]); if(curr_prio != 0){ while(!s.empty() && s.top() != '(' && isitoperator(s.top()) >= curr_prio){ out[k]=s.top(); s.pop(); k++; } } s.push(str[i]); } } while(!s.empty()){ out[k]=s.top(); s.pop(); k++; } out[k] = '\0'; cout<<endl<<"Postfix Result: "; for(int j=0;j<k;j++) cout<<out[j]; cout<<endl; } int main() { char str[m]="a+b*(c^d-e)^(f+g*h)-i"; infixtopostfix(str); return 0; }
现在运行代码,你应该能看到hello的打印,以及正确的后缀表达式输出了。
内容的提问来源于stack exchange,提问作者user46562
相关产品推荐
相关产品推荐

