do while loop

Feb 13, 2014 at 6:34am
I am trying to ask if a user is a boy or a girl. Everything works except the loop is infinite and I don't know what to change to make it work properly. Also I notice a lot of posts can paste the code onto this website and it looks like it does in the compiler, whereas mine is all black writing. How do I change that also?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  cout << "Are you a boy or a girl, my child?" << endl;
	string cGender;
	cin >> cGender;

	do
	{
		if (cGender == "Boy")
		{
			cout << "Oh boy! A boy you are indeed!" << endl;
		}
		else if (cGender == "Girl")
		{
			cout << "Oh alright, you are a girl I see!" << endl;
		}
		else
		{
			cout << "I'm sorry that is not a valid gender." << endl;
		} 
	} while (cGender != "Boy" || cGender != "Girl");
Feb 13, 2014 at 7:12am
Your mistake is in your loop condition. If you read carefully, you'll realize that the only way to exit your loop right now is if cGender is both equal to "Boy" and "Girl", which is simply not possible.

Rewrite your condition in a way that loops the code only if a non-valid gender is chosen.
Feb 13, 2014 at 7:23am
Read your loops condition logic. Your problem lies there.

You wouldn't really need to use a loop at all in that scenario for one; it's a straight comparison, display output, end. cGender isn't changing once you've entered the loop.

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
#include <iostream>
#include <string>

using namespace std;

int main() {
	
	string cGender;
	const string boy = "boy";
	const string girl = "girl";

	do {

		cout << "Are you a boy or a girl, my child?" << endl;
		cin >> cGender;

		if (cGender == boy)
		{
			cout << "\nOh boy! A boy you are indeed!\n" << endl;
		}
		else if (cGender == girl)
		{
			cout << "\nOh alright, you are a girl I see!\n" << endl;
		}
		else
		{
			cout << "\nI'm sorry that is not a valid gender.\n" << endl;
		}

	} while (cGender != boy && cGender != girl);
}


That condition is saying, if cGender is anything else but "boy" or "girl", loop again.
Last edited on Feb 13, 2014 at 7:52am
Feb 13, 2014 at 8:43am
Thank you very much mate that helped out quite nicely!
Topic archived. No new replies allowed.