How to use do while loop to display menu?

Hi everyone! I'm new to C++ and this is what I coded in the last few days:

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


using namespace std;

int main()
{ 

int  choice ;
float weight, weightE, weightJ, weightMA, weightME, weightN, weightP, weightS, weightU, weightV ;

	cout<<"*************************\n";
	cout<<"  Welcome to Planetor!\n";
	cout<<"*************************\n";
	cout<<"Please enter your weight in KG: ";
	cin>>weight;
	
	cout<<"***********************************\n";
	cout<<"Please choose one of the following:\n";
	cout<<"|-----------------|--------------------|"<<endl;
	cout<<"| Planet          |  Force of gravity  |"<<endl;
	cout<<"|-----------------|--------------------|"<<endl;
	cout<<"|1. Earth         |    1.00            |"<<endl;
	cout<<"|2. Jupiter       |    2.65            |"<<endl;
	cout<<"|3. Mars          |    0.39            |"<<endl;
	cout<<"|4. Mercury       |    0.38            |"<<endl;
	cout<<"|5. Neptune       |    1.23            |"<<endl;
	cout<<"|6. Pluto         |    0.05            |"<<endl;
	cout<<"|7. Saturn        |    1.17            |"<<endl;
	cout<<"|8. Uranus        |    1.05            |"<<endl;
	cout<<"|9. Venus         |    0.78            |"<<endl;
	cout<<"|-----------------|--------------------|"<<endl;
	cout<<" 10. Exit                               "<<endl;
	cout<<"                                        "<<endl;
	cout<<"Your choice: ";
	cin>>choice; 
	
	//codes
	
	
	else if (choice > 9 || choice < 1)    //user input validation
	{
	cout << "Invalid Input\n";
	//How to use do while loop to return to menu. 
	}
			
return 0;
}

The code is running fine. However, I want to program to re-display menu if user entered "Invalid Input" using do while loop. Is that possible? How?
Last edited on
There are many ways of doing this.
One such method runs like this in pseudocode:
Start with an invalid result
While ( result is invalid )
   write menu
   read result
   if ( result is invalid ) inform user
End while


Another method is to write a function to input a variable. The function can be called recursively if the input is invalid.


For your code the former method would look like:
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
	weight = -1;                                      // start with something invalid
	while ( weight <= 0 )                             // keep looping menu and input whilst invalid
	{
	    cout<<"Please enter your weight in KG: ";
	    cin>>weight;
	    if ( weight <= 0 ) cout << "Invalid input; please try again.\n";       // notify if invalid
	}
	
	choice = 0;
	while ( choice < 1 || choice > 10 )
	{
	    cout<<"***********************************\n";
	    cout<<"Please choose one of the following:\n";
	    cout<<"|-----------------|--------------------|"<<endl;
	    cout<<"| Planet          |  Force of gravity  |"<<endl;
	    cout<<"|-----------------|--------------------|"<<endl;
	    cout<<"|1. Earth         |    1.00            |"<<endl;
	    cout<<"|2. Jupiter       |    2.65            |"<<endl;
	    cout<<"|3. Mars          |    0.39            |"<<endl;
	    cout<<"|4. Mercury       |    0.38            |"<<endl;
	    cout<<"|5. Neptune       |    1.23            |"<<endl;
	    cout<<"|6. Pluto         |    0.05            |"<<endl;
	    cout<<"|7. Saturn        |    1.17            |"<<endl;
	    cout<<"|8. Uranus        |    1.05            |"<<endl;
	    cout<<"|9. Venus         |    0.78            |"<<endl;
	    cout<<"|-----------------|--------------------|"<<endl;
	    cout<<" 10. Exit                               "<<endl;
	    cout<<"                                        "<<endl;
	    cout<<"Your choice: ";
	    cin>>choice; 
	    if ( choice < 1 || choice > 10 ) cout << "Invalid input; please try again.\n";       // notify if invalid
	}



Your code is quite repetitive. Consider:
- Eliminating all those different weight variables - you don't need a different one for each planet.
- Use either parallel arrays for planet name, relative gravitational attraction OR (better) structs containing these. Then you won't need a long line of if blocks.


Oh, and just to be pedantic! ... Pluto has been relegated from the list of planets!
http://www.bbc.co.uk/news/science-environment-33462184
Last edited on
Regarding Pluto, it's my school work so I afraid I could not eliminate it in this case...hahaha.

I have not learnt pseudocode in the class yet, so I think starting with something simple like do-while loop first would be a lot easier.

Anyway, could you show an example to shorten those codes?
@zoren,

This thread makes zero sense if you remove your original code. Please do not do that. For consistency I include your original code at the bottom of this post. I think my solution did all that was necessary for this.

If you want a simple struct then
1
2
3
4
5
6
struct Planet
{
   string name;
   double relativeGravity;
   // add any other properties, like radius of orbit etc.
};

would be fine.

You can declare an array of planets like
1
2
const int NUM_PLANETS = 9;   // if you insist on keeping Pluto
Planet parray[NUM_PLANETS] = { { "Earth", 1.0 }, { "Jupiter", 2.65 }, ... }


You can loop through the array of type Planets just like you would an array of type ints etc. Refer to the ith planet's name as parray[i].name.


"pseudocode" is not something you learn in class. It's just a common-sense way of describing to yourself in your own language or slang the order of operations in a program. It is programming-language agnostic.


Just for the record this was your original 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>


using namespace std;

int main()
{ 

int  choice ;
float weight, weightE, weightJ, weightMA, weightME, weightN, weightP, weightS, weightU, weightV ;

	cout<<"*************************\n";
	cout<<"  Welcome to Planetor!\n";
	cout<<"*************************\n";
	cout<<"Please enter your weight in KG: ";
	cin>>weight;
	
	cout<<"***********************************\n";
	cout<<"Please choose one of the following:\n";
	cout<<"|-----------------|--------------------|"<<endl;
	cout<<"| Planet          |  Force of gravity  |"<<endl;
	cout<<"|-----------------|--------------------|"<<endl;
	cout<<"|1. Earth         |    1.00            |"<<endl;
	cout<<"|2. Jupiter       |    2.65            |"<<endl;
	cout<<"|3. Mars          |    0.39            |"<<endl;
	cout<<"|4. Mercury       |    0.38            |"<<endl;
	cout<<"|5. Neptune       |    1.23            |"<<endl;
	cout<<"|6. Pluto         |    0.05            |"<<endl;
	cout<<"|7. Saturn        |    1.17            |"<<endl;
	cout<<"|8. Uranus        |    1.05            |"<<endl;
	cout<<"|9. Venus         |    0.78            |"<<endl;
	cout<<"|-----------------|--------------------|"<<endl;
	cout<<" 10. Exit                               "<<endl;
	cout<<"                                        "<<endl;
	cout<<"Your choice: ";
	cin>>choice; 
	
	if (choice == 1) 
	{
   	weightE = weight*1.00;
	cout<<"Your weight on Earth is:  "<<weightE;
	}
	
	
	else if (choice == 2)
	{
	weightJ = weight*2.65;
	cout<<"Your weight on Jupiter is: "<<weightJ;
	}
	
	else if (choice == 3)
	{
	weightMA = weight*0.39;
	cout<<"Your weight on Mars is: "<<weightMA;
	}
	
	else if (choice == 4)
	{
	weightME = weight*0.38;
	cout<<"Your weight on Mercury is: "<<weightME;
	}
	
	else if(choice == 5)
	{
	weightN = weight*1.23;
	cout<<"Your weight on Neptune is: "<<weightN;
	}
	
	else if(choice == 6)
	{
	weightP = weight*0.05;
	cout<<"Your weight on Pluto is: "<<weightP;
	}
	
	else if (choice == 7)
	{
	weightS = weight*1.17;
	cout<<"Your weight on Saturn is: "<<weightS;
	}
	
	else if (choice == 8)
	{
	weightU = weight*1.05;
	cout<<"Your weight on Uranus is: "<<weightU;
	}
	
	else if (choice == 9)
	{
	weightV = weight*0.78;
	cout<<"Your weight on Venus is: "<<weightV;
	}

	else if (choice == 10)
	{
	cout<<"Program exiting..."<<endl;
	return 0;
	}
	
	
	else if (choice > 9 || choice < 1)    //user input validation
	{
	cout << "Invalid Input\n";
	//How to use bool and while loop to prompt menu. 
	}
			
return 0;
}

Last edited on
Hello Zoren,

Another alternative would be to put the menu in a function and call it when needed. Then you could do something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
do
{
	MainMenu();

	cout << "Your choice: ";
	cin >> choice;

	//codes


	if (choice > 9 || choice < 1)    //user input validation <--- The else will cause an error becuse there is no if.
	{
		cout << "Invalid Input\n";
		//How to use do while loop to return to menu. 
	}
} while (choice > 9 || choice < 1);


Or what I like to do is have "MainMenu" return the choice back to where it was called and put a do.while or while loop in the function, so it only returns a correct answer.

The above code would still apply,but you will have to replace "MainMenu();" with all your cout statements and define "choice" above the do/while loop and return choice after the do.while loop. This way everything is done in one function and the function can be called from anywhere.

Hope that helps,

Andy
@lastchance

Sorry I was trying to re-code the part you mentioned to be "repetitive" so it was temporary removed.
Hello Zoren,

This is something I like to do. See if it meets what you are looking for:

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//  How touse a do while loop to display a menu.cpp Entry point of program.
//
//  Written  01/29/2017
//
//  Finished //2017
//
//  By Zoren http://www.cplusplus.com/forum/beginner/229334/
//
/*
*/
//
//
//
//
//

#include <iostream>
#include <chrono>
#include <thread>

int MainMenu();

int main()
{
	int choice{};  // <--- Always good practice to initialize your variables.
	int weight{};

	std::cout << "*************************\n";
	std::cout << "  Welcome to Planetor!\n";
	std::cout << "*************************\n";
	std::cout << "Please enter your weight in KG: ";
	std::cin >> weight;

	choice = MainMenu();

	// <--- You could use a switch here to use the value of "choice".

	switch (choice)
	{
		case 1:
			// do something.
			break;
		case 10:
			break;  // <--- Do nothing except the switch or put a return 0; here.
		default:
			break;
	}
	return 0;
}  //  End main

int MainMenu()
{
	int choice{};

	do
	{
		std::cout << "\n***********************************\n";  // <--- Added \n at the begining.
		std::cout << "Please choose one of the following:\n";
		std::cout << "|-----------------|--------------------|" << std::endl;
		std::cout << "| Planet          |  Force of gravity  |" << std::endl;
		std::cout << "|-----------------|--------------------|" << std::endl;
		std::cout << "|1. Earth         |    1.00            |" << std::endl;
		std::cout << "|2. Jupiter       |    2.65            |" << std::endl;
		std::cout << "|3. Mars          |    0.39            |" << std::endl;
		std::cout << "|4. Mercury       |    0.38            |" << std::endl;
		std::cout << "|5. Neptune       |    1.23            |" << std::endl;
		std::cout << "|6. Pluto         |    0.05            |" << std::endl;
		std::cout << "|7. Saturn        |    1.17            |" << std::endl;
		std::cout << "|8. Uranus        |    1.05            |" << std::endl;
		std::cout << "|9. Venus         |    0.78            |" << std::endl;
		std::cout << "|-----------------|--------------------|" << std::endl;
		std::cout << " 10. Exit                               " << std::endl;
		std::cout << "                                        " << std::endl;
		std::cout << "Your choice: ";
		std::cin >> choice;

		if (choice > 10 || choice < 1)    //user input validation
		{
			std::cout << "\nInvalid Input\n";  // <--- Added \n at the begining.
			std::this_thread::sleep_for(std::chrono::seconds(3));  // Requires header files "chrono" and "thread"
			//How to use do while loop to return to menu. 
		}

		} while (choice > 10 || choice < 1);

	return choice;
}  // End MainMenu 


I did not see your if/else if statements until after I wrote this, but the switch will work in place of the if/else if statements.

Using the switch long with "choice" you could define the planet gravitates as constexpr double planteGravity[10]{ 0, 1.0, 2.65, 0.39, 0.38, 1.23, 0.05, 1.17, 1.05, 0.78 };. Then in the switch refer to the needed gravity as planteGravity[choice] in your math. in the switch you can do:
std::cout << "Your weight on Earth is: " << weight * planteGravity[choice]; and eliminate the need for all those different variables.

Hope that helps,

Andy
Topic archived. No new replies allowed.