I am doing infix to postfix notation. My program compiles, although, for some reason it will not take in any infix expressions, only postfix expressions. Which is the opposite I wanted to do. Here is my program:
#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;
}
For example the program runs like this:
If you like to see my stack class and header, if that is the problem please let me know. I can post it under reply.
Oh my, where to begin. You should probably take this to the Code Review Stack Exchange instead, but let's get into it: