Resolved Switch statement in c

Discussion in 'Mac Programming' started by CsRookie, Apr 16, 2011.

  1. CsRookie, Apr 16, 2011
    Last edited: Apr 17, 2011

    macrumors newbie

    Joined:
    Apr 13, 2011
    #1
    I am using a switch statement for a menu driven program. I am having trouble though.

    Lets say the menu has three choices,

    1) add inventory
    2) remove inventory
    3)view inventory

    Im not having any trouble jumping to the different functions, however, how do I get back to my menu in int main?

    If i add inventory and then want to go back to the menu, how do I get there? What type of statement or loop do I need?

    Thanks in advance :apple:
     
  2. macrumors G5

    gnasher729

    Joined:
    Nov 25, 2005
    #2
    Instead of acting on three different choices, just print out what menu choice the user made at the moment, or just print out that the user has made a choice, then figure out how to get another menu choice with the difficulty of the switch statement gone.

    Once you've done that, add the switch statement.

    (The principle at work: If you can't solve the whole problem in one go, you reduce the problem first, making it easier to solve, solve it, then continue solving the problems that you removed).
     
  3. macrumors Pentium

    KnightWRX

    Joined:
    Jan 28, 2009
    Location:
    Quebec, Canada
    #3
    Have you learned about loops ?

    Switch is not a looping mecanism, it's a conditional statement. Basically, a simplified if, elsif, else solution.

    The problem you have run accross is not switch itself, it's you're missing a looping statement where your menu will be displayed again and user input read again to then go into the switch statement again.

    What you essentially want is to run through your program multiple times.
     
  4. Moderator

    balamw

    Staff Member

    Joined:
    Aug 16, 2005
    Location:
    New England
    #4
    I think CsRookie already knows that, but only knows the words but not how to implement it.

    CsRookie. Can you post the code for our main and the switch statement you are using for the menu? It makes it a lot easier for us to help you if you give us as much specific/hard info as possible. Rather than say I've got a switch statement, show us the actual switch statement you are working with.

    What do you expect? What have you tried specifically that didn't work? ...

    EDIT: Read: http://whathaveyoutried.com and http://mikeash.com/getting_answers.html on how to post effectively in this kind of forum to get the answers you seek.

    EDIT 2: Don't forget that one of the menu choices should probably be

    4) Exit program.

    B
     
  5. macrumors 603

    notjustjay

    Joined:
    Sep 19, 2003
    Location:
    Canada, eh?
    #5
  6. macrumors Pentium

    KnightWRX

    Joined:
    Jan 28, 2009
    Location:
    Quebec, Canada
    #6
    You're right, missed that part. Quickly scanned it this morning before running out to the gym, just ignore my post then.
     
  7. thread starter macrumors newbie

    Joined:
    Apr 13, 2011
    #7


    Thanks for all the quick responses,

    Code:
    	printf("1. Add Vehicle\n");
    	printf("2. Remove Vehicle\n");
    	printf("3. Display One Vehicle\n");
    	printf("4. Display All Vehicles\n");
    	printf("5. Display vehicles by price range\n");
    	printf("6. Display vehicles by style\n");
    	printf("7. Terminate the program\n");
    	printf("\n Please enter your choice (1-7, then enter)");
    	scanf("%d",&choice);
    
    
    	switch (choice)
    	{
    	case 1: addCar(); break;
    
    There is a piece of the code, When i jump to the function addCar(); it goes just fine, but once I am done with add car and I want to go back to the main menu is where I am confused.

    Code:
    addCar(void)
    {	
    	struct car cars[5];
    	cars[i]=getCar();
    	printf("Return to menu? 1. to go to Menu\n");
    	printf("Add another vehicle enter 2\n");
    	scanf("%d", &selection);
    
    
    I have tried doing another switch statement after the input saying case 1 go back to displayMenu, but it always shows up with an error message of C2143 missing ; before type.

    Maybe I am going about this the wrong way, do I need a loop in the start of the program for the menu?

    Thanks for the replies :):apple:
     
  8. macrumors 603

    Joined:
    Aug 9, 2009
    #8
    Post complete code.
     
  9. macrumors G5

    gnasher729

    Joined:
    Nov 25, 2005
    #9
     
  10. jiminaus, Apr 16, 2011
    Last edited: Apr 16, 2011

    macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #10
    Your missing the critical part (highlighted in red) of the pseudocode I posted in other C Programming, menu? thread.

    Code:
    Initialize program
    [color=red]Loop[/color]
      Print menu on screen
      Read menu choice from keyboard
      Switch choice
      If menu choice is 1 then do view inventory
      If menu choice is 2 then do add inventory
      (etc.)
      If menu choice is 5 then exit loop
    [color=red]End loop[/color]
    Cleanup program
    
    So once execution hits the bottom of your addCar() function, for example, execution to returns to the next statement after the call. In the case it's the break statement in side the case 1 of your switch (choice) construct. Execution then jumps to after the switch. At that point you need to loop back to printing the menu if choice wasn't equal to 5.

    So refining the pseudo-code becomes:
    Code:
    Initialize program
    Do Loop
      Print menu on screen
      Read choice from keyboard
      Switch on choice
        When choice is 1: add vehicle
        When choice is 2: remove vehicle
        (etc.)
        When choice is 5: do nothing
        Otherwise: Gently facilitate user to enter make a choice
      End Switch
    Loop while menu choice != 5
    Cleanup program
    
     
  11. macrumors 6502a

    Joined:
    Jun 27, 2010
    #11
    Add in the loop in bold.

    Code:
    [B][SIZE="4"]while(1)
    {[/SIZE][/B]
    	printf("1. Add Vehicle\n");
    	printf("2. Remove Vehicle\n");
    	printf("3. Display One Vehicle\n");
    	printf("4. Display All Vehicles\n");
    	printf("5. Display vehicles by price range\n");
    	printf("6. Display vehicles by style\n");
    	printf("7. Terminate the program\n");
    	printf("\n Please enter your choice (1-7, then enter)");
    	scanf("%d",&choice);
    
    
    	switch (choice)
    	{
    	case 1: addCar(); break;
    	case 2: whatever2(); break;
    	.
    	.
    	.
    	case 7: exit(); break;
    	}
    [B][SIZE="4"]}[/SIZE][/B]
    
     
  12. macrumors 6502

    Joined:
    Apr 29, 2010
    #12
    Why not write "while (choice != 7)"?
     
  13. macrumors 603

    Joined:
    Aug 9, 2009
    #13
    A do/while seems even more suitable.
    Code:
    do { [I]...stuff...[/I] } while (choice != 7);
     
  14. macrumors 68020

    pilotError

    Joined:
    Apr 12, 2006
    Location:
    Long Island
    #14
    While your at it, you should also add a default at the bottom and print that the input value was incorrect.
     
  15. macrumors 6502

    Joined:
    Apr 29, 2010
    #15
    I agree. I'm a purist about coding style. So to me, an infinite loop seems needless when you already know the user can type a choice number to terminate the program. Since I'm not a C expert, I need to learn a lot about that language. Pascal, the language I know best, is nearly dead now, except in Lars's neck of the woods. ;)
     
  16. macrumors 603

    Joined:
    Aug 9, 2009
    #16
    No, it's just pining for the fjords.
     
  17. macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #17
    I was strongly influenced by Ada's loops. Unless it's immediately obvious which kind of loop is need, the way I code a loop it to start out with an infinite loop and code an explicit loop exit where-ever in the code that is most natural. The I look at the exit condition. If it's at the top, I transform the infinite loop into a while; if it's at the bottom, I transform the infinite loop into a do/while; otherwise I leave it as an infinite loop.

    Personally I find something like this:
    Code:
    for(;;) {
      // Input data
      if (I/O error) {
        // Abort due to I/O error
      }
      if (EOF) {
        break;
      }
      // Process data
    }
    
    to be superior to:
    Code:
    // Input data
    if (I/O error) {
      // Abort due to I/O error
    }
    while (EOF) {
      // Do more
      // Input data
      if (I/O error) {
         // Abort due to I/O error
      }
    }
    
    in terms of maintainability because it upholds the principal of "do not repeat yourself".

    I've heard objections that infinite loops with explicit breaks cause trouble when people skim code. But if you skim my functions, you'd typically missed the function altogether. I break my code down into the smallest functions possible. Small leaf functions are highly testable, and giving names to as many chunks of code as possible goes toward fulfilling my goal of self-documenting code.

    (I'm getting a sense of deja vu. Have we had this discussion before Bill?)
     
  18. macrumors 6502a

    Joined:
    Jun 27, 2010
    #18
    It seemed to me that the OP was actually trying to code something and not just doing this for learning or for a class.

    Hence, I suggested the infinite loop as it will be the one that is the most simple to understand and to type out.

    However, if the OP is trying to learn, then definitely, there do exist more elegant solutions
     
  19. thread starter macrumors newbie

    Joined:
    Apr 13, 2011
    #19
    Thank you guys for all the suggestions and responses. I got it to work properly now and have added the suggestions that were made. Thank you again for the help and responses. :):apple:
     
  20. macrumors 6502

    Joined:
    Apr 29, 2010
    #20
    Jimianus makes good points about infinite loops, repeating yourself. I have no problem with breaking out of an Ada loop-statement because the language's designers designed that statement to be terminated with a break. I have problems, only stylistic ones, with breaking out of a any loop in C when the loop condition is still true. I prefer languages that force me to write in disciplined ways. So I prefer, say, Python to Perl. Python gives me a few clear, understandable ways to do things that Perl or C would let me do in many ways. The permissiveness can tempt some to write clever code that may be hard to understand or even ugly.

    I do what jimianus does: I write tiny functions, especially in Lisp. In fact, when I tried to solve the "inventory menu" problem that someone posted here, I kept wondering one function should print a menu before another one read the user's choice. I thought, "Menu printing is a general job. I could write a program where a function read both a menu and a list of choices from a file. So to print another menu, I first get another menu from another menu file."

    Yup, jimianus is having deja vu.
     

Share This Page