我正在使用后缀表示法的中缀。我的程序编译,但由于某种原因它不会接受任何中缀表达式,只有后缀表达式。这与我想做的相反。这是我的计划:
#include <iostream>
#include <string>
#include <sstream>
#include "stack"
using namespace std;
string infixexpr (istream& in)
{
//Holds value in computation
stack<string> postfixstack;
//used to to read in characters from the expression
char ch;
// used to read in numbers from expression
int num;
// Used to remove infix expressions from stack
string lexpr, rexpr;
ch = in.peek();
while ( ch != EOF)
{
//If we have a whitespace character skip it and continue with
// the end of the loop.
if(isspace(ch))
{
ch = in.get();
ch =in.peek();
continue;
}
//nonspace character is next to input stream
// if the next character is a number read it and convert it
// to string then put the string onto the postfix stack
if (isdigit (ch))
{
in >> num;
// use to convert string
ostringstream numberstr;
// convert to number using sstream
numberstr << num;
// Push the representing string onto stack0
postfixstack.push(numberstr.str());
ch = in.peek();
continue;
}
// if operator pop the two postfix expressions
// stored on the stack, put the operator after
postfixstack.pop();
lexpr = postfixstack.top();
postfixstack.pop();
if (ch == '+' || ch == '-' || + ch == '*' || ch == '/' || ch == '%')
postfixstack.push(rexpr + " " + lexpr + " " + ch);
else
{
cout << "Error in input expression" << endl;
exit(1);
}
ch = in.get();
ch = in.peek();
}
return postfixstack.top();
}
int main()
{
string input;
cout << "Enter a infix expression to convert to postfix,"
<< " \nor a blank line to quit the program:";
getline(cin,input);
while (input.size() != 0 )
{
//convert string to a string stream
istringstream inputExpr(input);
cout << "the infix equavilent is: "
<< infixexpr(inputExpr) << endl;
cout << "Enter a infix Expression to evaluate: ";
getline(cin,input);
}
return 0;
}
例如,程序运行如下:
如果您想查看我的堆栈类和标题,如果这是问题,请告诉我。我可以在回复时发布。
答案 0 :(得分:1)
哦,我的,从哪里开始。 你应该把它带到Code Review Stack Exchange而不是,但让我们进入它: