alright... I'm writing a program and my switch statement seems to be causing an infinite loop in certain circumstances.
When putting in the case numbers, the program works just fine... but when putting in any non-number character (letters, for instance), it enters an infinite loop. My default seems to do nothing.
Also, if I input certain numbers ( 9 and 10, for instance), it doesn't trigger the default... but other numbers do (6 through 8)...
I've tried everything I could think of. I've searched google and this forum. I'm using Microsoft Visual Studio .NET 2003
Here's the entire program.
Code:#include "stdafx.h" using std::cout; using std::cin; using std::endl; using std::fixed; #include <iomanip> using std::setprecision; int main() { int product; int quantity; double product1 = 2.98; double product2 = 4.5; double product3 = 9.98; double product4 = 4.49; double product5 = 6.87; double total = 0; cout << "We offer the following products: \n\nProduct 1 = $"<< product1 << "\nProduct 2 = $" << fixed << setprecision( 2) << product2 << "\nProduct 3 = $" << product3 << "\nProduct 4 = $" << product4 << "\nProduct 5 = $" <<product5 << endl << endl; cout << "Enter the product number you would like to purchase (-1 when finished): "; cin >> product; while ( product != -1 ) { switch ( product ) { case 1: cout << "Please enter the quantity you would like to purchase: "; cin >> quantity; total = total + ( product1 * quantity ); break; case 2: cout << "Please enter the quantity you would like to purchase: "; cin >> quantity; total = total + ( product2 * quantity ); break; case 3: cout << "Please enter the quantity you would like to purchase: "; cin >> quantity; total = total + ( product3 * quantity ); break; case 4: cout << "Please enter the quantity you would like to purchase: "; cin >> quantity; total = total + ( product4 * quantity ); break; case 5: cout << "Please enter the quantity you would like to purchase: "; cin >> quantity; total = total + ( product5 * quantity ); break; case '\n': case '\t': case ' ': break; default: //catch all other characters cout << "Incorrect character entered." << endl; break; } cout << "Enter the product number you would like to purchase (-1 when finished): "; cin >> product; } cout << "\nThe total of all purchases is $" << fixed << setprecision( 2 ) << total << endl; return 0; }