Using for loop correctly

Hi, so the code that i am writing is suppose to allow the user 3 entries but i am unsure of how to properly make it work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  	for (i = 0; i > 4; ++i);
		{
			getline(cin, guess);
			if (guess == answer)
			{
				cout << "Congratulation you chose correctly." << endl;
			}
			else if (guess != answer)
			{
				cout << "You guessed well but......WRONG" << endl;
			}
		}
		cout << "Do you want to play again Yes/No?" << endl;
		getline(cin, run);

	} while (run == "Yes");

	return 0;
for (i = 0; i > 4; ++i); // <--semicolon and loop never runs because 0 < 4
Also you probably want to exit the loop when the user guess the answer, so you need to add break after your "Congratulations ..." message
change line 1 to:
for (int i = 0; i < 3; ++i)
Also you probably want to exit the loop when the user guess the answer, so you need to add break after your "Congratulations ..." message


Another method would be to put a second condition in the for loop some people don't like break statements.

for( int i = 0; i < 3 && guess != answer; ++i )

Though I personally like to use while loops when you don't have a set number of times to loop.

1
2
3
4
5
6
7
int i = 0;

while( i < 3 && guess != answer )
{
   //see if they have correct guess
    ++i;
}
So the code still does not want to run the loop 3 times, here is where i currently am.

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
srand((unsigned)time(NULL));

	do {
		ranhint = rand() % 7;
		string answer = vcolour.at(ranhint);
		string guess = vhints.at(ranhint);
		cout << (vhints[ranhint]) << endl;
		cout << "Remember to put your answer in lower case please." << endl;
		

		for (i = 0; i < 3; ++i);
		{
			getline(cin, guess);
			if (guess == answer)
			{
				cout << "Congratulation on a job well done." << endl;
			}

			else
			{
				cout << "You guessed well but......WRONG" << endl;
			}
		}
	
		cout << "Do you want to play again Yes/No?" << endl;
		getline(cin, run);

	} while (run == "Yes");

and when i try and set guess > i it will not run because guess is a string and i is an int.
Well yours is missing a condition to stop the loop when the guess was found look at the earlier replies. You are going to want to loop only and only if i < 3 and guess != result.
You are still not removing that semi colon I mentioned in my first post. Your loop runs 3 times but since you have the semicolon, the block of code under the loop is only executed after the for-loop has finished
Last edited on
Topic archived. No new replies allowed.