I am trying to solve a problem that evaluates simple expressions in a string like 10+20
should return 30
The problem is the string can contain white spaces so i uses stringstring
with skipws
flag it works for white spaces within the string like 10 + 20
etc but when white space is in the end its not passing towards the correctly.
This is how I am parsing the string
void build_stack(const string& str) {
istringstream ss(str);
char op;
int op1, op2;
ss>>skipws>>op1;
operands.push(op1);
while(!ss.eof()) {
ss>>op;
operators.push(op);
ss>>op2;
operands.push(op2);
}
}
full code with various string inputs here in rextester.
when the string is 3+5 / 2
my stacks gets built as
operands => 2 2 5 3
operators => / / +
when the string is 3+5 / 2
(i.e with trailing whitespace) my stacks gets built as
operands => 2 5 3
operators => / +
i tried
while(ss.peek() == ' ') {
char c; ss>>c;
}
but this is removing all characters after seeing a whitespace.