Hey everybody. I have a practice question I am tackling from a beginners C++ book regarding loops (while, do-while, & for), and would like to know if I am approaching this correctly and if I can simplify my code to include fewer lines.
Here is the question from the book:
"Write a menu program that lets the user select from a list of options, and if the input is not one of the options, reprint the list."
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string a = "1", b = "2", c = "3", d = "4";
string input;
do
{
cout << "Choose from one of the following four choices: \n";
cout << a << ": This is choice 1.\n" << b << ": This is choice 2.\n" << c << ": This is choice 3.\n" << d << ": This is choice 4.\n";
cout << "Enter your choice: ";
cin >> input;
if (input == "1")
{
cout << "Your choice is 1.\n";
break;
}
if (input == "2")
{
cout << "Your choice is 2.\n";
break;
}
if (input == "3")
{
cout << "Your choice is 3.\n";
break;
}
if (input == "4")
{
cout << "Your choice is 4.\n";
break;
}
cout << "\n";
}
while (1);
}
It looks like when I posted this the formatting changed a bit. I copied it straight from my compiler, however, it doesn't look quite like this. My apologies.
If you edit your post, highlight your code, then click the <> button in the Format palette on the right side of the post, that will format your code on the forum.
If they're entering a single number, I'd probably make the input type a char or int. You don't really need the separate variables for each option, at least in this program. You can have the while condition check for entries outside of the 1 to 4 range. I took out all the separate break statements. Instead of an if/else statements, you could also do this with a switch statement.
Thanks. This helps me think of different ways to execute code in situations like this. I initially tried to use the "or" operator as well, but with no success, and I like to the use of the ">" sign. Much appreciated for the response and assistance.
Thanks as well for the response. I'm going to experiment with what you both have recommended to practice a bit more with not only this particular exercise, but other loop scenarios as well.
You could make it much smaller, but then it would just look bad. That's not what it's all about. I like having readable code. This is how i would do it btw. Switch cases instead of a bunch of if and else if statements.