Hello all. I'm trying to teach myself c++ in my spare time. To assist in that, I'm writing a basic program, just for learning purposes. It asks for several words, and uses them in a sentence. I've got that working. Now I'm going a step further and asking the sex of a previously inputted Name. The reply must be either Male or Female, if not, I want it to ask again for a correct reply. This would run as a continual loop until a correct answer is given. Easy enough, you would think.
The answer I've found in my searching looks like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
string name;
cout<<"Enter a name: \n";
getline (cin, name);
// Determine the sex of name
string sex;
cout<<"Is "<<name<<" male, or female? \n";
getline (cin, sex);
// Enforce a male or female response, or loop forever
while ((strcmp (sex, "male") != 1) || (strcmp (sex, "female") != 1))
{
cout<<"No, really. You have to chose one of the above. Male, or Female? \n";
getline (cin, sex);
}
|
This code works if I use plain words (ex: "male", and "female", above) without using a string (ex: sex, above). Two strings or one, it fails with the following error:
loop.cpp:27: error: cannot convert 'std::string' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'
I have tried to substitute "char*" for "string" in the relevant places in the code, using cin instead of getline, etc. I can make it compile then, but it fails to run past that point. It gives me "Bus error", and exits to prompt.
In case it matters, I'm compiling with G++ on OS X (or sometimes with G++ on my Debian Intel server via SSH, but it doesn't seem to matter which system).
I have found that I can substitute the following code, and it works, but it seems like this is just a workaround, and not the "right" way to do it? Correct me if I'm wrong...
while ((sex != "male") && (sex != "Male") && (sex != "female") && (sex != "Female"))
In other words, the program runs and behaves as expected, but since this is a learning exercise, I want to learn the correct/preferred way to do this. Thanks in advance.