PDA

View Full Version : [Resolved] Switch statement in c




CsRookie
Apr 16, 2011, 02:06 AM
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:



gnasher729
Apr 16, 2011, 02:30 AM
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:

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).

KnightWRX
Apr 16, 2011, 06:47 AM
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.

balamw
Apr 16, 2011, 06:55 AM
What type of statement or loop do I need?


it's you're missing a looping statement

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

notjustjay
Apr 16, 2011, 10:30 AM
I Googled the search term "loop forever" and this was one of the first hits:

http://www.saskschools.ca/~ehs/HeiseIntra/C/Lesson67.html

KnightWRX
Apr 16, 2011, 11:17 AM
I think CsRookie already knows that, but only knows the words but not how to implement it.


You're right, missed that part. Quickly scanned it this morning before running out to the gym, just ignore my post then.

CsRookie
Apr 16, 2011, 11:26 AM
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



Thanks for all the quick responses,


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.


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:

chown33
Apr 16, 2011, 11:48 AM
Post complete code.

gnasher729
Apr 16, 2011, 11:52 AM
[QUOTE=CsRookie;12403571]Thanks for all the quick responses,


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;


I get some idea where the problem comes from. The function "addCar()" that you call has nothing to do with the menu. It is not its business at all to go back to the menus. Its business is to add a car. That's why I said: For the moment, throw the whole switch statement out and replace it with

printf ("User chose menu %d\n", choice);

and add what is needed to go back to the menu choice (at this point your program will run forever because you have no code yet to terminate it). When that is done, do what is needed to finish the program when the user enters "7". And when that is done, you can put back the code to handle menus 1 to 6.

jiminaus
Apr 16, 2011, 05:41 PM
Your missing the critical part (highlighted in red) of the pseudocode I posted in other C Programming, menu? thread.


Initialize program
Loop
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
End loop
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:

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

SidBala
Apr 16, 2011, 10:10 PM
Add in the loop in bold.


while(1)
{
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;
}
}

Bill McEnaney
Apr 17, 2011, 12:19 AM
Add in the loop in bold.


while(1)
{
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;
}
}


Why not write "while (choice != 7)"?

chown33
Apr 17, 2011, 01:19 AM
Why not write "while (choice != 7)"?
A do/while seems even more suitable.
do { ...stuff... } while (choice != 7);

pilotError
Apr 17, 2011, 07:13 AM
While your at it, you should also add a default at the bottom and print that the input value was incorrect.

Bill McEnaney
Apr 17, 2011, 03:53 PM
A do/while seems even more suitable.
do { ...stuff... } while (choice != 7);
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. ;)

chown33
Apr 17, 2011, 04:25 PM
Pascal, the language I know best, is nearly dead now, except in Lars's neck of the woods. ;)

No, it's just pining for the fjords.

jiminaus
Apr 17, 2011, 04:30 PM
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. ;)

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:

for(;;) {
// Input data
if (I/O error) {
// Abort due to I/O error
}
if (EOF) {
break;
}
// Process data
}


to be superior to:

// 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?)

SidBala
Apr 17, 2011, 06:24 PM
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

CsRookie
Apr 17, 2011, 11:04 PM
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:

Bill McEnaney
Apr 18, 2011, 09:18 PM
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.