[英]a code for infix to postfix conversion
I have written a code for infix to postfix conversion,This piece of code is not encountering any kind of compile time error but after taking the input infix expression it is giving some runtime errors which i am unable to understand these errors are something related to string as the message says. 我已经写了一个用于后缀转换的代码,这段代码没有遇到任何编译时错误,但是在输入了输入后缀表达式后,它给出了一些运行时错误,我无法理解这些错误与字符串有关如消息所示。
#include<iostream>
#include<string>
#define N 50
using namespace std;
class stack
{
private:
char arr[N];
int tos;
public:
void push(char p)
{
if (tos != N)
arr[++tos] = p;
else
cout << "stack full";
}
char pop()
{
if (tos == -1)
cout << "stack Empty";
else
return (arr[tos--]);
}
bool isempty()
{
if (tos == -1)
return (true);
else
return (false);
}
char top()
{
return arr[tos];
}
stack()
{
tos = -1;
}
};
int pres(char sym)
{
if (sym == '^')
return 3;
else if (sym == '*' || '/')
return 2;
else if (sym == '+' || '-')
return 1;
else if (sym == '(')
return 0;
}
bool isoperator(char op)
{
if (op=='+' || op=='-' || op=='/' || op=='*' || op=='^')
return true;
else
return false;
}
int main()
{
string infix, postfix;
stack s;
int in=0;
int post=0;
cout << "Enter an infix expression: ";
cin >> infix;
s.push('(');
infix.append(")");
char temp;
while (!(s.isempty()))
{
if (isdigit(infix[in]))
postfix[post++] = infix[in];
else if (infix[in] == '(')
s.push(infix[in]);
else if (infix[in] == ')')
{
while (1)
{
temp = s.pop();
if (temp == '(')
break;
else
postfix[post] = infix[in];
}
}
else if (isoperator(infix[in]))
{
while (pres(s.top()) >= pres(infix[in]))
postfix[post++] = s.pop();
s.push(infix[in]);
}
in++;
}
cout << "Postfix expression is: " << postfix;
system("pause");
}
I m unable to get what's wrong with it. 我无法弄清问题所在。 Can any one help??
可以帮忙吗?
I found the following logical errors in your code: 我在您的代码中发现以下逻辑错误:
postfix
is empty at the beginning, but you're writing to single character positions using postfix[post++]=
. postfix
在开始时为空,但是您正在使用postfix[post++]=
写入单个字符位置。 This is not valid and is propably causing the "string related" errors. postfix.push_back()
to add characters to the output string. postfix.push_back()
将字符添加到输出字符串。 In the first inner while
loop ( while(1)
) the last statement should read 在第一个内部
while
循环( while(1)
)中,最后一条语句应读取
postfix.push_back(temp);
since you want to append the operators from the stack to the output. 因为您要将运算符从堆栈追加到输出。
pop()
function) for detecting input errors. pop()
函数中检查空堆栈)以检测输入错误。 The biggest error is in his pres() function, it should be: 最大的错误在于他的pres()函数,应该是:
else if (sym == '*' || sym == '/')
else if (sym == '+' || sym == '-')
I have noticed some of the errors mentioned by MartinStettner. 我注意到MartinStettner提到的一些错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.