Here is the snippet of code I am having issues with.

    cout<<"So are you a male or female,  Please type m/f"<<endl;
    cin>>sex;

    if (sex='M','m') 
    {
    alcohol_distribution=.73;
} 
    else if (sex='F','f') 
    { 
    alcohol_distribution=.66;
}

So I know I have this terribly wrong, but i want the alcohol_distribution based on whether or not the user is a male or female. thank you very much.

Dani AI

Generated

A few practical points that build on 's correction and make the input handling safer and more predictable for future readers.

Read a full line, extract the first non-space character, normalize its case, then decide. This accepts "M", "m", "male", etc., and avoids surprises from leftover input. Use named constants for the distribution values and validate the input so the program can re-prompt or fail gracefully.

Example pattern:

#include <string>
#include <cctype>

double alcohol_distribution = 0.0;
std::string input;
std::getline(std::cin, input);

if (!input.empty()) {
  char c = std::tolower(static_cast<unsigned char>(input.front()));
  const double MALE_DIST = 0.73;
  const double FEMALE_DIST = 0.66;

  if (c == 'm') alcohol_distribution = MALE_DIST;
  else if (c == 'f') alcohol_distribution = FEMALE_DIST;
  else {
    // handle invalid input: re-prompt, set default, or exit
  }
}

Notes and gotchas:

  • Cast to unsigned char before calling std::tolower to avoid undefined behavior on signed char. See std::tolower reference.
  • Prefer std::getline over operator>> if you want to accept words like "male" or handle trailing whitespace reliably.
  • The original if (sex='M','m') uses assignment and the comma operator, which ends up testing the right-hand value and will not behave as intended. Comparing normalized characters (as above) avoids that class of bug.
  • For larger programs, represent the choice with an enum or boolean rather than scattering magic numbers through the code.

Recommended Answers

All 2 Replies

if (sex=='m' || sex == 'M') { /* ... */ }

Note the use of == rather than = and the use of ||.

thank you so much that helped perfectly!:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.