一种根据输入的顺序分组输入的方法
A way to sort out inputs according to the order they are inputted?
,所以我正在研究一个程序,该程序将infix表达式并将其转换为后缀表达式。意思是当我输入A B时,输出将为AB ,并且我无法找到正确打印出来的方法,因为我无法想到一种分类字母的方法,例如如何将输入A B-C转换为AB c-代替ABC - ?源代码仍在进行中。
#include <iostream>
#include <stack>
using namespace std;
int prec(char in)
{
switch(in) {
case '(': return 0;
case '+':
case '-': return 1;
case '*':
case '/': return 2;
default : return 3;
}
}
int main()
{
stack <char> ops;
//stack <char> high-ops;
char next_character ;
while(!cin.eof()) {
cin >> next_character;
if(next_character =='(' )
ops.push('(');
else if(next_character == ')') {
while(!ops.empty() && ops.top() != '(') {
cout << ops.top();
ops.pop();
}
if(!ops.empty())
ops.pop();
else
cout << "Error/n";
}
if((next_character >= 'a' && next_character <= 'z') || (next_character >= 'A' && next_character <= 'Z') || (next_character >= '0' && next_character <= '9'))
if(next_character == '*' || next_character == '/' || next_character == '+' || next_character == '-') {
if(ops.empty())
ops.push(next_character);
if(prec(next_character) > prec(ops.top()))
ops.push(next_character);
if(prec(ops.top()) > prec(next_character)) {
cout << ops.top();
ops.pop();
if( prec(ops.top()) == prec(next_character)){
ops.push(next_character);
cout << ops.top();
ops.pop();
}
}
}
//if(!ops.empty())
//ops.push(next_character);
}
while(!ops.empty()){
cout << ops.top();
ops.pop();
}
}
您需要递归解析,而不是基于堆栈的解析。
在psuedo代码中,看起来像这样:
func reorder(expression)
if whole_expression_is_wrapped_with_parentheses
return reorder(expression without wrapping parentheses)
if exists_operator(expression)
oi = operator_index = find_operator(expression)
before = expression.substring(0 to oi-1, including)
operator = expression.charAt(oi)
after = expression.substring(oi + 1 to end of string)
return reorder(before) + reorder(after) + oi
return expression
func exists_operator(expression)
Simply check if any operator is in the expression out of parentheses.
func find_operator(expression)
Return the id of the first operator found out of parentheses.
To implement precedence, ignore lower precedence operators until making sure no higher precedence operators are in the expression
应使用基于堆栈的括号计数器实现两个辅助功能,以确保您仅搜索任何括号。
相关文章:
- 如何从输入的文本文件中按姓氏字母顺序对图表进行排序?
- 函数以相反的顺序输出输入问题,并改进算法以解释相等的数字
- 如何以相反的顺序读取C++程序的输入
- `sTD :: sample()的输出序列是否遵循输入序列的顺序
- 如何使用C 扭转输入文件的顺序
- 一种根据输入的顺序分组输入的方法
- 按字母顺序打印结构输入C
- 检查用户输入是否按字母顺序排列
- std::map 的排序顺序取决于输入值
- 当我以不同的顺序输入值时,程序会出错
- C++按顺序读取多个输入文件
- C++ 输入流:Solaris 与 Linux 中的操作顺序
- C++学习映射输入的顺序
- 输入流运算符查找顺序与Boost.Program_options
- 在几个顺序数组元素中输入相同的值
- 通过ifstream输入的字符串在存储到数组之前按字母顺序排序,寻求建议
- 从输入中读取单词序列。使用"Quit"终止,按输入顺序打印,不要打印两次单词。
- 如何在c++中按字母顺序对标准输入字符串排序
- 简单的输入/输出控制台应用程序,不按给定的顺序(结构)打印问题
- Qt库中的mapreduce是否保留输入文件的顺序?