Using loops

A section in my code needs to ask if you want to add, subtract, or exit. I cant get it to keep looping as long as you don't want to exit. What is wrong with this code. (ive changed stuff for simplicity on here.)

1
2
3
4
5
6
7
8
9
10
11
  cout << "Choose an operation: Addition (a), Subtraction (s), Exit (e): ";
	cin >> choice;
	while (choice == 'a' && choice == 's' && choice == 'e');
	{
		if (choice == 'a')
			cout << "numbers added";
		if (choice == 's')
			cout << "anumbers subtracted";
		if (choice == 'e')
			cout << "program terminates";
	}
Your cin is out of the while loop so it can only request one input from the user and that's it. I'm guessing you might want to change && to || because choice can never be 'a', 's' and 'e' at the same time. Because of that, your loop will never actually run.

The reason why it gives you results at the moment is because you have a ; at the end of the while statement. Your while statement is not doing anything, it's just there for show and the prog jumps straight to the if statements.

Try while(cin >> choice) and add a break; under choice == 'e'.
Also, your if statements never break, so it will never actually exit out of the loop. That, and it would probably be better to use else statements in front of each subsequent if statement, simply for the case of not having to evaluate the state of choice 3 times when you already found the value you were looking for the first time (not really necessary here when there's 3 values to evaluate, but when you make, say, a program that calculates prime numbers, you don't want to have to divide 10362 by every single prime number before just to realize it's divisible by 2).
Last edited on
Topic archived. No new replies allowed.