What loop should I use? If any?

Hi everyone,

I am wondering what loop I need to use for when the condition is not met.
I want to make it so that when the user enters a letter other than 'h' or 'l', the user will be redirected to the question.

How would I do that?

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
int main()
{
	srand((unsigned)time(NULL));
	cout<<"Welcome" <<endl;

	int comp1=rand()%101+1;
	int comp2=rand()%101+1;
	char choice;

	cout<<"The computer has generated the number:"<<comp1<<endl;
	cout<<"Do you think the next number will be higher or lower? Please enter 'h' or 'l'.";
	cin>>choice;

	
	if(choice=='h'||choice=='H')
	{
		cout<<"The computer has generated the number:"<<comp2<<endl;
		if(comp2 > comp1)
		{
			cout<<"Congratulations! You win!"<<endl;
		}
		else 
		{
			cout<<"I'm sorry. You lose!"<<endl;
		}
	}
	else if(choice=='l'||choice=='L')
	{
		cout<<"The computer has generated the number:"<<comp2<<endl;
		if(comp2 < comp1)
		{
			cout<<"Congratulations! You win!"<<endl;
		}
		else
		{
			cout<<"I'm sorry. You lose!"<<endl;
		}
	}
	else
	{
		cout<<"Invalid input."<<endl;
	}
You could use a while loop like this:

1
2
3
4
5
6
7
bool InvalidInput = choice != 'h' || choice != 'H' || choice != 'l' || choice != 'L';

while( InvalidInput )
{
    cout<<"Incorrect user input! Please enter another value." <<endl;
    cin>>choice;
}
I think the above code won't work. InvalidInput is not updated inside while loop. Use
while( choice != 'h' || choice != 'H' || choice != 'l' || choice != 'L'; ) or enter InvalidInput = choice != 'h' || choice != 'H' || choice != 'l' || choice != 'L'; inside while loop.


eypros wrote:
I think the above code won't work.
Well spotted!

1
2
3
4
5
6
7
8
9
bool InvalidInput = true;

while( InvalidInput )
{
    cout<<"Incorrect user input! Please enter another value." <<endl;
    cin>>choice;

    InvalidInput = choice != 'h' || choice != 'H' || choice != 'l' || choice != 'L';
}

There you go! I hope that'll work. But if it doesn't I'm sure you can work out the rest!

Good luck!
Topic archived. No new replies allowed.