I'm working on a project to convert from postfix to infix expressions. I was stuck for a while but I had part of it working then I realized I needed to inlcude a space between each of the operands when I input it to the user.I'm not sure how to take in a string and not include spaces how would I go about doing that. getline doesn't work as it includes spaces. therefore instead of ab+ I need to accept it as: a b +. i'm not sure how to do this not include the strings. Here is my code so far.
#include "stack.h"
void convert(string expression){
stack c;
string post =" ";
string rightop="";
string leftop="";
string op ="";
for (int i =0; i<=expression.length()-1;i++){
c.push(expression[i]);
c.print();
if (expression[i] == '*' ||
expression[i] == '+' ||
expression[i] == '-' ||
expression[i] == '/'){
cout<<c.top()<<endl;
leftop=c.top();
cout<<leftop<<endl;
c.pop();
rightop=c.top();
cout<<rightop<<endl;
c.pop();
op=c.top();
cout<<op<<endl;
c.top()=expression[i+1];
//c.pop();
post="(" + leftop + " " + op + " " + rightop + ")";
cout<<post<<endl;
}
//c.push(post);
}
}
int main(){
string expression;
cout<<" Enter a Post Fix expression: ";
getline(cin,expression);
convert(expression);
return 0;
}
In C, strings are essentially a bunch of character pointers. You can refer to this SO post for a few examples of how to remove white space from your input string by moving pointers.
You can test explicitely each character against
" \t\r"
, or you can use theisspace
function declared incctypes
:I've update my answer to your other question with that.