Thread: Need help with switch/case selection structure

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    5

    Need help with switch/case selection structure

    Good afternoon all. Here is a function that accepts an int data type for 'product' and selects the appropriate case. I need help with the 'default' option. If a user enters a bad value, I would like the default case to execute and allow the user to reenter a number option( suing cin>>product). Once the default option is executed, how do I get the program to return to the top of this function for cin>>product; and reselect the appropriate case?


    Here's the code..................

    int productSelection()
    {
    cin>>product; //User's menu choice, var declared
    //in main()


    if(product!=-1)
    { //begin TRUE path
    switch(product)
    {
    case 1:
    sandwich();
    break;
    case 2:
    chips();
    break;
    case 3:
    drink();
    break;
    case 4:
    totalSale();
    break;
    default:
    cout<<"You entered and incorrect option."<<endl;
    cout<<"Please enter another option or enter"<<endl;
    cout<<"-1 to end the program."<<endl;
    break;
    } //end of switch
    } //end of TRUE path
    else
    { main();} //returned to main for end
    } //end of productSelection

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >how do I get the program to return to the top of this function for cin>>product; and reselect the appropriate case?
    Use a loop?

    >{ main();} //returned to main for end
    That looks suspicious, especially since calling main recursively isn't legal in C++.
    My best code is written with the delete key.

  3. #3
    Useless Apprentice ryan_germain's Avatar
    Join Date
    Jun 2004
    Posts
    76
    why dont you put your switch in a do-while?? something like:
    Code:
    do{
            cout << "enter blah blah";
            cin >> parameter;
            
            //switch goes here
            //...
            //default: cout << "you entered incorect data";
    }while(parameter < whatever && parameter > something);
    hope it helps

  4. #4
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Code:
    bool select(int);
     
    int main()
    {
      int product;
      bool anotherChoice = true;
      while(anotherChoice) 
    	 anotherChoice = select(product);
    }
     
    bool select(int product)
    {
      cin >> product;
      //menu goes here.
      switch (product)
      {
    	case -1:
    	  return false;
    	//a bunch of other cases go here
    	default:
    	  cout << "inappropriate input.  try again" << endl;
    	  break;
      }
      return true;
    }
    Here's one approach. Because you state that product is declared in main() it will not be visible in select() unless you pass it to select() from main(). Therefore I passed it as a parameter by value given that's easier to understand than passing it by reference. The loop in main() will continue to function as long as anotherChoice is true. The only way for anotherChoice to be set to false is if product is -1 and the appropriate case is called in the switch statement.

  5. #5
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903

    Here is an example

    Hello

    I would like to offer some of my own code as a possible example on how one would set up a typical switch/case menu. This also introduces a "try / throw/ catch" exception handling scenario. For "Default:" however, most people just cout a message stating something to the effect, "Invalid entry, please try again."

    The 'Do/While' loop structure allows the user to execute the menu as many times as desired.. or as many times as there is an invalid entry.




    Code:
    int main()
    {
    
    data stack;
    
    char choice = 'x';
    
    system("cls");
    
    	do
    	{
    		try
    		{
    			print_menu();
    			choice = toupper(get_user_command());
    			switch(choice)
    			{
    		
    				case 'A':	stack.push();
    							break;
    
    				case 'R':	stack.pop();
    							break;
    
    				case 'V':	view_array();
    							break;
    		
    				case 'E':	stack.erase_array();
    							break;
    
    				case 'Q':	exit_message();
    							break;
    		
    				default:	throw choice;
    			}		
    
    		}
    			
    		catch(char choice)
    		{
    			cout << "\n\t" << choice << " is an invalid entry.  Please try again." << endl;
    		}
    
    		cout << endl;
    		system("pause");	
    		system("cls");
    
    	}while (choice != 'Q');
    
    
    	
    
    return EXIT_SUCCESS;
    
    }

    Please feel free to ask any questions
    Last edited by The Brain; 06-28-2004 at 08:10 PM. Reason: to correct spelling errors.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >This also introduces a "try / throw/ catch" exception handling scenario.
    Invalid input is not really an "exceptional circumstance" because it happens too often and readily. Because exceptions have no overhead except when thrown but have considerable overhead once thrown, you should restrain yourself to truly exceptional occurances that can't be easily handled without unwinding the stack. In this case, the try/catch only serves to complicate matters and one can do away with it very easily. In other words, don't bludgeon a fly with a sledgehammer when a rolled up magazine will work.
    My best code is written with the delete key.

  7. #7
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    don't bludgeon a fly with a sledgehammer when a rolled up magazine will work.
    That is soooo getting quoted. But of course using a sledge is fun at times

  8. #8
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    hey! There's already a brain here!

    I'll sue.
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  9. #9
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903

    Hi :)

    Nice name btw, fillyourbrain
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  10. #10
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    It's not much....


    but its my own...


    my precious.
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  11. #11
    Registered User
    Join Date
    Jun 2004
    Posts
    5
    I just wanted to thank everyone for the help and suggestions. I am new to c++ and this is the second program I am trying to develop. Our CS class books are not updated or very good and our class assignments are challenging. I appreciate what you all have done.

    Thank you.

  12. #12
    Registered User
    Join Date
    Jun 2004
    Posts
    5
    Oh, here is another way I was trying to solve the problem. I am using a void function to dispaly a menu template that has a specific output format. The function is a void function with the following handle:

    void menu(int &sandwichQty, double &sandwichCost,...)

    My goal is to create a function that will display updated data to the screen in a specific format. What I am trying to do is use the menu function to accept data from other functions that calculate accumulator totals and pass that data by reference to the menu() which has a specified format. I want to use the menu() just for displaying and updating the data. Is this a valid function?

    Code:
    void menu(int &sandwichQty, double &sandwichCost,...)
    {                            //create menu interface.
        
        cout<<"**************************************"<<endl;
        cout<<"*******  Snack Bar Register  *********"<<endl;
        cout<<"****************************************"<<endl;
        cout<<endl;
        cout<<endl;
        cout<<"\t  S -       SANDWICH       - $3.00"<<endl;
        cout<<"\t  C -        CHIPS         - $1.50"<<endl;
        cout<<"\t  D -     LARGE DRINK      - $2.00"<<endl;
        cout<<"\t  T - Calculate Total Sale -  $$$"<<endl; 
        cout<<"\t  X - Cancel Sale and Start Over - ";
        cout<<endl;
        cout<<endl;
        cout<<"****************************************************"<<endl;
    cout<<"*******************************************"<<endl;
    cout<<"Item Purchased"<<"\t Quantity"<<"\t SaleAmount"<<endl;
    cout<<"********************************************"<<endl;
    
    cout<<"Sandwich"<<'\t'sandwichQty<<'\t'sandwichCost;
    etc
    etc
    Is this a valid function?


    Thanks again

  13. #13
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903

    Lightbulb void print menu();

    Looks good to me


    the only possible issue I see... are sandwichQty and sandwichCost private class member variables?

    IF so: you will need to pass in "accessor" functions to return sandwichQuantity and sandwichCost.

    For example:
    Code:
    int get_quantity(){ return sandwichQuantity; }    //Class Member Function Prototype
    so the parameter list for void menu might look like this:

    Code:
    void menu(int get_quantity(), double get_cost())
    Using "accessor" functions will allow you access to, and return the value of your private class member variables. Just 'cout' a function call to your accessor wherever you would want to 'cout' the value of sandwichQuantity or sandwichCost.


    IF not: then what you have should work
    Last edited by The Brain; 06-29-2004 at 08:15 PM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  14. #14
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You may also want to make your function constant, since the menu function doesn't actually change anything.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem referencing structure elements by pointer
    By trillianjedi in forum C Programming
    Replies: 19
    Last Post: 06-13-2008, 05:46 PM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  3. Tab Controls - API
    By -KEN- in forum Windows Programming
    Replies: 7
    Last Post: 06-02-2002, 09:44 AM
  4. Serial Communications in C
    By ExDigit in forum Windows Programming
    Replies: 7
    Last Post: 01-09-2002, 10:52 AM
  5. C structure within structure problem, need help
    By Unregistered in forum C Programming
    Replies: 5
    Last Post: 11-30-2001, 05:48 PM