Trouble with cstrings

I am having trouble with cstrings. I have worked with strings, but never cstrings. I'm trying to make something where the user is prompted to enter in their gender, and then if it is male the program will output male and vice versa.

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
#include "stdafx.h"
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
	char a[10];
	cout<<"Are you a male or a female"<<endl;
	cin.getline(a,10);
	int i=0;
	while(a[i])
	{
	if(a[i]=="male")
	{
		cout<<"male"<<endl;
	}
	if(a[i]=="female")
	{
		cout<<"female"<<endl;
	}
	}
	getchar();
	return 0;
}
I have worked with strings, but never cstrings.

You probably should keep it that way.
You can't compare C strings using operator==, you have to use strcmp.
a is an array of char; a will devolve to a char-pointer, pointing at a[0], anywhere it can that you use it.

a[i] is a single char. One char.

"male" is a string literal, which returns a pointer to the 'm' somewhere in memory. So this:

a[i]=="male" is an attempt to compare a single char value with a char-pointer value. Hopefully, it's clear to you that that won't work.

You might think this would do it:

if (a == "male")

but that is comparing a pointer to a[0] to the pointer to the 'm', and since a[0] and the 'm' are in different places in memory, you'd be comparing different pointers with different values. Again, that's not right.

In this case, what needs to happen is a[0] needs to be compared to the character m, and then a[1] to the character a, and so on. This is a pain to write, so we have the function strcmp to do it for us. It lives in <cstring>. Please look it up.
you are doing int i=0; and than
1
2
3
4
5
6
7
8
9
10
11
while(a[i])
{
	if(a[i]=="male")
	{
		cout<<"male"<<endl;
	}
	if(a[i]=="female")
	{
		cout<<"female"<<endl;
	}
}

you are not doing anything with i that means a[0] = male how can that be ever true.
Topic archived. No new replies allowed.