Error checking my menu, stuck on one thing

When a user enters a number that is not 1 or 2, how can I make my function restart?

I would like my "else if" snippet to restart the menuList function so that the user has a second chance to enter a choice.

Do I need to initialize my functions from within a loop in order to do this? Maybe put the menuList function inside of a do while loop? Any ideas? And if I do a loop, can I make it a part of a class?

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
 #include <iostream>
#include <fstream>
#include <string>


using namespace std;

void switchCase(int);
int menuList();
//void displayResult();


int main()
{

   switchCase(menuList());


}

int menuList()
{

    int z;
    cout << "Menu" << endl;
    cout << "1. Edit File" << endl;
    cout << "2. Exit" << endl;
    cin >> z;

    return z;
}




void switchCase(int menuChoice)
{


if (menuChoice == 1 || menuChoice == 2)
{
    cout << "ok" << endl;
}

else if (menuChoice != 1 || menuChoice != 2)
    cout << "Please select an option from the menu and try again. " << endl;
    menuList();

}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
void switchCase(int menuChoice)
{
    if (menuChoice == 1 || menuChoice == 2)
    {
        cout << "ok" << endl;
    }
    else if (menuChoice != 1 || menuChoice != 2)
    {
        cout << "Please select an option from the menu and try again. " << endl;
        switchCase(menuList());
    }
}
HAHAHA wow do I feel stupid right now. Thank you.

So this is like perfection. If the user decides that they want to slam their head into the keyboard, everything is going to start over again. And it will keep doing that until the head slammer manages to hit a 1 or a 2.

Gonna post my code in final form just in case anyone has a similar question:

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
using namespace std;

void switchCase(int);
int menuList();
//void displayResult();


int main()
{

   switchCase(menuList());


}

int menuList()
{

    int z;
    cout << "Menu" << endl;
    cout << "1. Edit File" << endl;
    cout << "2. Exit" << endl;
    cin >> z;

    return z;
}




void switchCase(int menuChoice)
{


if (menuChoice == 1 || menuChoice == 2)
{
    cout << "ok" << endl;
}

else if
    (menuChoice != 1 || menuChoice != 2)
{

    cout << "Please select an option from the menu and try again. " << endl;
    switchCase(menuList());
}

}
Last edited on
Topic archived. No new replies allowed.