Trying to learn loops (practice problem)

I have tried to solve this using different loops and loops with if statements. I keep getting compile errors no matter what I do. I finally tried a do-while loop and the code below finally compiles but it seems to be a infinate loop. Can someone please point me in the correct direction. I have searched for answers, and worked on this for two days now. I have completed all the other exercises for this chapter but this one. For some reason I just can't get my head around it.

Here is the problem:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
using namespace std;

int main ()
{
	string option;
	do
	{
	cout << "Please make a selection 1 - 4 below:" << endl;
	cout << "1) One" << endl;
	cout << "2) Two" << endl;
	cout << "3) Three" << endl;
	cout << "4) Four" << endl;
	getline( cin, option, '\n' );
	} while ( option !=  "1" || "2" || "3" || "4" );

cout << "You have chosen " << option << endl;
return 0;
}
This is incorrect:
while ( option != "1" || "2" || "3" || "4" )

What you're saying right now is "keep looping as long as any one (or more) of the following are true:
-- option != "1"
-- "2" evaluates to non-zero (always true)
-- "3" evaluates to non-zero (always true), or
-- "4" evaluates to non-zero (always true)."
Hence the infinite loop.

So it should be
while (option != "1" && option != "2" && option != "3" && option != "4").

In reality, you don't need a string for this -- you can just make option an int, in which case you can just do
while (option < 1 || option > 4).
Topic archived. No new replies allowed.