Going back to the menu without using goto

Aug 28, 2011 at 8:26am
Hi!

Can someone teach me how to get back to the main menu of the program without using goto.

such as this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
USER_MENU:
 printf("\n[1] Encode File");
 printf("\n[2] Decode File");
 printf("\n[3] Exit\n");
 printf("\nWhat do you want to do? ");
 scanf("%d", &a);

 switch(a) {
 case 1:
      //open file input.txt for reading
      f_input = fopen("input.txt", "r");
      if(f_input == NULL){
        printf("\nFile input.txt was not found!!");
		printf("\nFind the file and select again.\n");

        printf("\n");
		goto USER_MENU;
      }


I want to learn how to substitute those goto's

BTW, The main menu of the program is the
printf("\n[1] Encode File");
printf("\n[2] Decode File");
printf("\n[3] Exit\n");
printf("\nWhat do you want to do? ");
Last edited on Aug 28, 2011 at 8:26am
Aug 28, 2011 at 8:42am
Use a loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bool quit = false;
while(!quit){
  printf("\n[1] Encode File");
  printf("\n[2] Decode File");
  printf("\n[3] Exit\n");
  printf("\nWhat do you want to do? ");
  scanf("%d", &a);

  switch(a) {
  case 1:
    //open file input.txt for reading
    f_input = fopen("input.txt", "r");
    if(f_input == NULL){
      printf("\nFile input.txt was not found!!");
      printf("\nFind the file and select again.\n");
      printf("\n");
    }
    break;
  case 3:
    quit = true;
    break;
}
Aug 28, 2011 at 8:44am
if im right, this is what you would want to do
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//this int is just an example
int temp;
temp=1;
//while temp doesnt = 0
while(temp !=0)

printf("\n[1] Encode File");
 printf("\n[2] Decode File");
 printf("\n[3] Exit\n");
 printf("\nWhat do you want to do? ");
 scanf("%d", &a);
//first switch, which doesnt end the loop.
{
switch(a)
{
case 1: do stuff
break;
};
//second switch, which does end the loop because it makes the value of temp 0.
switch(b)
{
case 2: do stuff
temp = 0;
break;
};
}


thats the best as i can understand that you are wanting to do. i hope this helps! ^_^

Aug 28, 2011 at 9:18am
@hamsterman
I cant understand the use of the additional case 3?
What does it do?
Aug 28, 2011 at 9:36am
essentially, it switches the value of "quit" from "no" to "yes" and forces the loop to end. im kind of new at switches and flubbed my example. sorry
Aug 28, 2011 at 9:50am
ok thanks for the replies! Thanks to you both!
Topic archived. No new replies allowed.