问题
here is my code to convert infix to ron using shunting yard . I know how the algorithm works well and I have no problem with that . but when I run this just nothing happen . when I debug it I get unknown error on stack initialization line
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <stack>
using namespace std ;
void convert (char *) ;
double eval(char *) ;
int precedence(char);
int main() {
cout << "\n Enter an expression :\n" ;
cout << " >> " ;
char input[51] ;
cin.get(input,50);
convert (input) ;
system("PAUSE");
}
int precedence(char op) {
switch (op) {
case '-' : case '+' :
return 1 ;
case '*' : case '/' :
return 2 ;
case '^' :
return 3 ;
default :
return 0 ;
}
}
void convert(char* exp) {
stack <char> stc;
string outputQueue ;
// string temp ;
while (*exp) {
while (isspace(*exp)){
*exp++ ;
}
if (*exp == '(') {
stc.push(*exp++) ;
}
else if (*exp == ')'){
while (stc.top()!='(') {
outputQueue += stc.top() ;
stc.pop();
*exp++;
}
stc.pop() ; /** Havaset bashe */
}
else if (isdigit(*exp)){
while (isdigit(*exp)) {
outputQueue += *exp++ ;
}
outputQueue += " " ;
}
else if (strchr("+-*/^",*exp)) {
if (precedence(*exp) > precedence(stc.top())) {
stc.push(*exp++) ;
}
else {
if (precedence (*exp) == precedence (stc.top()) && precedence(*exp) == 3) {
stc.push(*exp++) ;
}
else {
outputQueue += stc.top() ;
outputQueue += ' ' ;
stc.pop();
}
}
}
}
while (!stc.empty()) {
outputQueue =+ stc.top() ;
stc.pop();
}
cout << outputQueue ;
}
回答1:
I don´t know what you mean, i fix the code. In 2 lines you try to get the top element of an empty stack. This produce a assert break.
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <stack>
using namespace std ;
void convert (char *) ;
double eval(char *) ;
int precedence(char);
int main()
{
cout << "\n Enter an expression :\n" ;
cout << " >> " ;
char input[51] ;
cin.get(input,50);
convert (input) ;
system("PAUSE");
}
int precedence(char op)
{
switch (op)
{
case '-' :
case '+' :
return 1 ;
case '*' :
case '/' :
return 2 ;
case '^' :
return 3 ;
default :
return 0 ;
}
}
void convert(char* exp)
{
stack <char> stc;
string outputQueue ;
while (*exp)
{
while (isspace(*exp))
{
*exp++ ;
}
if (*exp == '(')
{
stc.push(*exp++) ;
}
else if (*exp == ')')
{
while (stc.top()!='(')
{
outputQueue += stc.top() ;
stc.pop();
*exp++;
}
stc.pop() ; /** Havaset bashe */
}
else if (isdigit(*exp))
{
while (isdigit(*exp))
{
outputQueue += *exp++ ;
}
outputQueue += " " ;
}
else if (strchr("+-*/^",*exp))
{
if (precedence(*exp) > precedence(stc.top()))
{
stc.push(*exp++) ;
}
else
{
if (precedence (*exp) == precedence (stc.top()) && precedence(*exp) == 3)
{
stc.push(*exp++) ;
}
else
{
outputQueue += stc.top() ;
outputQueue += ' ' ;
stc.pop();
}
}
}
}
while (!stc.empty())
{
outputQueue =+ stc.top() ;
stc.pop();
}
cout << outputQueue ;
}
来源:https://stackoverflow.com/questions/17501175/convert-infix-to-rpn-shunting-yard