Repeating Loop
Aug 16, 2014 at 1:26pm UTC
This is a totally trivial console program but I'm new to cpp and I can't figure out how to make the menu redisplay if the user inputs the wrong answer.
Thanks in advance!
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
#include <iostream>
#include <string>
using namespace std;
int DisplayMenu(int x); // function prototype to display the menu
int main()
{
enum MenuChoice // enumerate the choices for the menu
{
Red,
White,
Blue,
Green,
Cyan
};
//string Color = "";
int ChosenColor = 0;
int MenuChoice = 0;
do
{
cout << "Choose a color by typing 1-5" << endl << endl;
cout << "1.\tRed" << endl;
cout << "2.\tWhite" << endl;
cout << "3.\tBlue" << endl;
cout << "4.\tGreen" << endl;
cout << "5\tCyan" << endl << endl;
cout << "Your choice? " ;
cin >> MenuChoice;
} while ((MenuChoice > 0 || MenuChoice < 6); // loops while MenuChoice does is greater than zero but less than 6)
if (MenuChoice > 0 || MenuChoice < 6)
{
cout << endl << "The user selected " << MenuChoice << endl; // debug code
}
// break;
cin.ignore();
cin.get();
return 0;
}
.
Aug 16, 2014 at 2:33pm UTC
This line:
} while ((MenuChoice > 0 || MenuChoice < 6);
should look more like:
} while (MenuChoice < 1 || MenuChoice > 5);
By the way, there's no point in writing comments which merely restate what the code itself says. A comment should add some value, such as explaining the overall intention of a block of code, or to clarify the non-obvious.
Aug 16, 2014 at 3:37pm UTC
Thank you for your response.
I changed the line, however, the menu does not re-display if the user enters a number out of the range.
Aug 16, 2014 at 4:24pm UTC
Then what does happen when an out of range number is entered?
This was my version, however i changed a number of things, but the important one was really the condition of the while loop.
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
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// Next two lines should be kept in agreement.
enum MenuChoice { Red=1, White, Blue, Green, Cyan };
const string colours[] = { "" , "Red" , "White" , "Blue" , "Green" , "Cyan" };
int Choice = Red;
do
{
cout << "Choose a color by typing " << Red << "-" << Cyan << "\n\n" ;
for (int i=1; i<6; i++)
cout << setw(3) << i << setw(8) << colours[i] << endl;
cout << "\nYour choice? " ;
cin >> Choice;
} while (Choice < Red || Choice > Cyan); // loops while Choice is out of range
cout << endl << "The user selected " << colours[Choice] << endl;
cin.ignore();
cin.get();
return 0;
}
Last edited on Aug 16, 2014 at 4:29pm UTC
Topic archived. No new replies allowed.