0

I am building a console bot. There is a way to specify the gender of the user there. Now if the user gives the command !setgender then the gender of the user will be asked by the bot. My question is the user can enter male, Male, mAle, maLe, malE ,mALE or any form of "male" the user wants (same goes for female and other gender). How can I get any form of "male" (or female, or other) and set the gender to Male (or female or other)?

einpoklum
  • 118,144
  • 57
  • 340
  • 684
Rid
  • 397
  • 2
  • 12
  • @Botje No it does not. – Rid Oct 21 '20 at 08:05
  • 2
    Why not? Once you case-fold the input to all-lowercase `"male"` you can compare against it. – Botje Oct 21 '20 at 08:06
  • I want to show the gender to `Male` @Botje – Rid Oct 21 '20 at 08:11
  • What is stopping you? `/* use linked answer to make data lowercase */ if (data == "male") data = "Male";` Done. StackOverflow is not a code writing service, you're still supposed to think for yourself. – Botje Oct 21 '20 at 08:12
  • Yeah, I was thinking about that. Currently i am implementing it. Let's see it works or not, I will notify you in 10 mins – Rid Oct 21 '20 at 08:14
  • Yeah it worked! I implemented the first answer of this question! Thanks for your help too – Rid Oct 21 '20 at 08:35
  • FahimFuad: So, you chose to go with lower-casing the string like @Botje suggested. In that case - this question is a dupe as suggested earlier. – einpoklum Oct 21 '20 at 08:48

2 Answers2

3

Transform the input to all lowercase, then the only valid input is "male" (shamelessly copied and adopted from here):

#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>


std::string data;
std::cin >> data;
std::transform(data.begin(), data.end(), data.begin(),
    [](unsigned char c){ return std::tolower(c); });
if (data == "male") {
    data = "M41e"; // whatever you like to have as the "correct" spelling
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

Reference

#include <cctype>
#include <iostream>
#include <string>
bool caseInSensStringCompare(const std::string &str1, const std::string str2)
{
    return ((str1.size() == str2.size()) &&
            std::equal(str1.begin(), str1.end(), str2.begin(), [](char c1, char c2) {
                return (c1 == c2 || std::toupper(c1) == std::toupper(c2));
            }));
}

int main()
{
    std::string gender;
    std::cin >> gender;
    if (caseInSensStringCompare(gender, "male"))
    {
        // ...
    }
}
Nitin Singla
  • 106
  • 2
  • 9
  • 1
    While it works, that function should probably take its arguments as const reference, and the lambda should just take chars instead of references to chars. – Botje Oct 21 '20 at 08:26
  • @Botje - Thanks to your tips, updated the answer :) – Nitin Singla Oct 21 '20 at 08:35