Loop help!

Pages: 12
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
#include <iostream>
using namespace std;


void first()
{
    int flag = 0;
    int sentinel = 999;

	int attempts = 0;
    
    while (flag != sentinel && ++attempts <= 6)
	{
		cout << "Please input value:  \n" << endl;
		cin >> flag;

		if (flag < 10)
		{ 
			cout << "The wire is: White" << endl;
		}
		else 
		if (flag < 30)
		{
			cout << "The wire is: Green" << endl;
		}
		else
		if (flag < 40)
		{
			cout << "The wire is: Blue" << endl;
		}
		else
		{
			cout << "The wire is: Red" << endl;
		}
	}

	if(attempts > 6)
		cout << "You have run out of 6 attempts.\n" << endl;
	else
		cout << "The program ends manually by user.\n" << endl;
}	

int main()
{
	cout << "Kaitlin N. Stevers" << endl;
	cout << "September 25, 2016" << endl;
	cout << "\t\t" << endl;
	cout << "\t\t" << endl;
	cout << "Before beginning, you need to know in order to end the loop you need to input the value 999." << endl;
	first();
}
Last edited on
SakurasouBusters wrote:
1
2
3
4
int flag;
int sentinel = 999;
int attempts = 0;
while ( flag != sentinel && ++attempts <= 6 )

That is still undefined behaviour (unlike in OP's version).
That is still undefined behaviour (unlike in OP's version).

Integers always represent the exact values. So it can't be undefined behavior.

It is just that flag happens to contain garbage value (it doesn't matter).
It is just that flag happens to contain garbage value (it doesn't matter).

It matters. The garbage can be exactly 999. The chance is tiny, but but it does exist. That, by definition is undefined behaviour.

It does not cost you much to explicitly prevent the uncertainty.
int flag = 0;


My first input to your program is 999. Why is it "red"? The 999 is supposed to stop the loop.
Undefined behaviour and bad logic. You can do better than that.


@OP:
A while loop:
1
2
3
while ( condition ) {
  body
}

will repeatedly execute the body as long as the condition is true. Therefore, something should affect the condition.
1
2
3
4
5
int input = 0;
int count = 0;
while ( std::cin >> input && input != 999 && count < 6 ) {
  ++count;
}

Here, if input operation fails, then the loop ends.
If input (that can be different each time) equals 999, the loop ends.
If 6 iterations have already occurred, the loop ends.
In any other case the loop keeps repeating.
closed account (ENhkSL3A)
Guys, I keep saying this, I can not set it to six times. It says it in the original post. Please read my whole post before replying. Thanks for trying to help me but it isn't helping when everyone's telling me to do something I can't. I got my program to work. So it's been solved but thanks for trying to help me.
Topic archived. No new replies allowed.
Pages: 12