Simple menu, infinite loop

Feb 11, 2009 at 7:49pm
Hey guys (and gals). I'm pretty new to programming, and was hoping that somebody could help me figure out where I've gone wrong. Here's my code:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void option1()
{    printf("You have selected option 1\n");}

void option2()
{    printf("You have selected option 2\n");}

void option3()
{    printf("You have selected option 3\n");}

void option4()
{    printf("You have selected option 4\n");}

int get_option()
{
    printf("Menu:\n\n");
    printf("1) One\n");
    printf("2) Two\n");
    printf("3) Three\n");
    printf("4) Four\n");
    printf("5) Five\n");
    printf("Please select option 1-5:  ");
    int opt;
    scanf("%d", &opt);
    return opt;
}

int main()
{
    int i = get_option();  
    while (i < 1 || i > 5)
    {
        printf("You have entered an invalid input character.  Please try again.\n\n");
        i = get_option();
    } 
     
    if (i == 1)
        option1();
    else if (i == 2)
        option2(); 
    else if (i == 3)
        option3();
    else if (i == 4)
        option4();
    else if (i == 5)
        exit(1);
           
system("pause");
return 0;
}


Basically, I'm just presenting the user with a menu of options, and prompting them to enter one. If they enter a valid number, then the function corresponding to that number is executed (at this point, the functions are pretty worthless). If they don't enter a valid number or character, they are supposed to be notified of that, presented the menu again, and prompted to enter another number. At this point, mine works okay unless a non-numeric value is entered, in which case it loops on indefinitely.

Any suggestions on how to get it to respond "normally" to a character or string input (i.e. so that it just informs the user that they entered invalid input, and allows them to try again) rather than going crazy??? Thanks.
Feb 11, 2009 at 7:57pm
Topic archived. No new replies allowed.