do while loop won't stop for input after first loop

Hi, I am trying to write a program that converts a postfix expression to infix. It works just fine on the first go-around. But when I try to convert another expression, it skips all the user input and terminates. (The sample input I used was simply ab+). Why is this happening? Could anyone give me some advice as to how to fix this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
 #include <iostream>
#include <string>
#include "stack.h"

using namespace std;

//prototypes
string toInfix(string);


int main()
{
	string postfix;  //postfix expression
	char choice;

	do{
		cout << "Enter a postfix expression: ";
		getline(cin, postfix);

		cout << "Postfix expression is: " << postfix << endl;
		if (postfix.length() <= 1)
		{
			cout << "ERROR: This is not a valid postfix expression. Terminating program" << endl;
			exit(1);
		}
		
		cout << "New infix expression is: " << toInfix(postfix) << endl << endl;
		cout << "Would you like to convert another expression? (y/n)";
		
		cin >> choice;
		cout << endl << endl;
	} while (choice == 'y' || choice == 'Y');
	return 0;
}




//definitions
string toInfix(string postfix)
{
	stack opStack;
	string infix, operand1, operand2, expr, token;
	

	for (int i = 0; i < postfix.length(); i++)
	{
		token = postfix.substr(i, 1);
		if (token == " ")
		{
			break;  //do nothing, skips blanks
		}
		if (token == "+" || token == "-" || token == "*" || token == "/" || token == "%")
		{
			operand2 = opStack.pop();
			operand1 = opStack.pop();
			expr = "(" + operand1 + token + operand2 + ")";
			opStack.push(expr);
		}
		else
		{
			opStack.push(token);
		}
	}
	infix = opStack.pop();
	return infix;
}
Last edited on
You probably have something in the input buffer that is being accepted as your new expression.
Try this and see if it helps.

include the <limits> header

#include <limits>
after line 30, add the following so it looks like
1
2
3
4
5
6
		cin >> choice; // your original code
		// new lines begin
		cin.clear();    // reset state of cin
		cin.ignore(numeric_limits<streamsize>::max(), '\n'); // discard all input until end of line
		// end of new lines
		cout << endl << endl; // your original code continues 

Not sure about that stack business...

You need to clear out the cin buffer. After line 31 add in:

1
2
cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );


You also have to include

#include <limits>
Awesome. Thank you so much for the great responses; clearing the buffer worked perfectly.
Topic archived. No new replies allowed.