switch statement bug

hey guys, this code is copied almost exactly from Bjarnes Stroustrups book and i cannot find the bug thats making me have to tel it to quit twice for some reason

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
#include <iostream>

int main()
{

	int lval = 0;
	int rval;
	char op;

	std::cout<<"Enter an expression:";
	std::cin>>lval;

	while(std::cin>>op)
	{
		std::cin>>rval;

		switch(op)
		{
		case '+':
			lval += rval;
			break;

		case '-':
			lval -= rval;
			break;

		case '*':
			lval *= rval;
			break;

		case '/':
			lval /= rval;
			break;

		case 'q':
			std::cout<<"Result: "<<lval<<std::endl;
			system("Pause");
			return 0;
		}

	}


}


i checked it like 3 times and this is super trivial stuff so you can imagine how irritating it is that i cant get it to work

EDIT: Please dont mind system i know you guys hate it, i just need a quick pause - i have tried it with the default case instead of q but its the same issue. i can even scan the code from the book if you guys desire
Last edited on
closed account (zb0S216C)
Try removing std::cin>>op (sic) from the condition and use std::cin.good( ) in its place. Then, place std::cin>>op (sic) above std::cin>>rval (sic). Like this:

1
2
3
4
5
6
while( std::cin.good( ) )
{
    std::cin >> op >> rval;

    // Switch statement...
}


Wazzak
Topic archived. No new replies allowed.