program crashes

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

		if (input == '(')  // '(' has lowest precedence in the stack, highest outside
			mystack.push(input);
		else if (input == ')')
			while (!mystack.empty() and mystack.top() != '(')
				cout << mystack.top();
				mystack.pop();
			if (!mystack.empty())
				mystack.pop();
			//else error  // no matching '('

		else if( input == '*' || input == '/' || input == '+' || input == '-')
			if (mystack.empty() || prec(mystack.top()) < prec(input)) // bottom of stack has lower precedence than everything
				mystack.push(input);
			else // prec(top of stack) >= prec(input)
				while (!mystack.empty() && prec(mystack.top()) >= prec(input)){
					cout << mystack.top();
					mystack.pop();
				}
				mystack.push(input);
		//else check for errors
while (!mystack.empty())
	cout << mystack.top();
	mystack.pop();

}
}


Thanks.
Last edited on
closed account (i23CM4Gy)
cin is most likely taking an input longer than one byte.

Add #include <cstdio> .
Then change line 22 to while ((input = getchar()) != EOF) {.

Then, modify the program so that input is an int so that the possibly negative value of EOF can be used regardless of what the platform says about the signed-ness of char.


Well, looks like I learned something about how cin works! :)
Last edited on
If I change input to an int then when I cout the input it will return a integer value instead of a character.
closed account (i23CM4Gy)
Use static_cast<char> or use printf(). So something like:

cout << static_cast<char>(input) << '\n'; or
printf("%c\n", input);
Last edited on
THe while loop at line 34 only executes line 35, not lines 35 and 36 as the indentation would suggest. I urge you to always use braces, even when you execute just a single line.

The else at line 41 matches the if at line 37, not the one at line 33 as the indentation suggests.

Line 49 executes whether or not the if statement at line 42 is true, not within the else clause as the indentation suggests.

Line 31 executes if the input is a letter. Is this what you intended? I suspect that lines 24 and 26 should start with else if instead of if.

With all these issues it's hard for me to tell what the program is supposed to do. Can you give a sample input and the expected output?

Input: 3+4

expected output: 34+
Last edited on
Got it working. This was all caused by indentation errors by not using the braces. Stupid of me but thanks for the reminder dhayden.
Topic archived. No new replies allowed.