[prog] switch statement

Wolf Rising wolfrising at gmail.com
Thu Dec 16 14:31:10 EST 2004


Is this what you meant? It still seems to run the same, maybe I missed
something? :-)
Thank you for responding :-)

#include <iostream>
using namespace std;

int main() {

//define variables
  int  product = 1; // product to be ordered
  int  quantity;//quantity to be ordered
  double price;
  double cost; // calculate cost
  double totalSales;


// Get input from user

//order product desired by product number
  cout << "Enter the product number (enter 0 to end): ";
//receive product number
  cin >> product;


//begin loop, set product to break from loop when sentinel value is entered
while (product > 0) {

//begin switch statement, define prices of product by number
switch ( product) {
   case 0:
    price = 0.00;
    break;

   case 1:
     price = 2.98;
     break;

   case 2:
     price = 4.50;
     break;

   case 3:
     price = 9.98;
     break;

   case 4:
     price = 4.49;
     break;

   case 5:
     price = 6.87;
     break;

   default:
    cerr << "INCORRECT NUMBER ENTERED. PLEASE TRY AGAIN. \n";
//      cout << "Enter the product number: ";
//      cin >> product;
    break;



}

 

//order quantity of product desired
  cout << "Enter the quantity of this product you wish to order: ";
//receive quantity
  cin >> quantity;

//calculate cost
  cost = quantity * price;

  cout << "Enter the product number: ";
  cin >> product;


  totalSales += cost;

}


  cout << "The total sales in dollars is: " << totalSales;
  
return 0;
}


On Thu, 16 Dec 2004 14:07:15 +1100, Gareth Anderson
<somecsstudent at gmail.com> wrote:
> Personally I'd restructure the program, maybe like this:
> 
> "
> int product = 1;
> 
> //begin loop, set product to break from loop when sentinel value is entered
> while (product > 0) {
> 
> //order product desired by product number
>  cout << "Enter the product number (enter 0 to end): ";
> //receive product number
>  cin >> product;
> 
> //begin switch statement, define prices of product by number
> switch ( product) {
>  case 0: break; (you don't want a zero to jump to default case)
>  case 1:
>     price = 2.98;
>     break;
> 
>   case 2:
>     price = 4.50;
>     break;
> 
>   case 3:
>     price = 9.98;
>     break;
> 
>   case 4:
>     price = 4.49;
>     break;
> 
>   case 5:
>     price = 6.87;
>     break;
> 
>   default:
>    cerr << "INCORRECT NUMBER ENTERED. PLEASE TRY AGAIN. \n";
>    break;
> }
> 
> Note changed cout to cerr and you can see the rest :)
> 
> Note that I finished second year (mostly C/C++ programming) in
> November so this could be a little rusty :)
> 
> Regards,
> Gareth
>


More information about the Programming mailing list