How to check if a char is in a string in C++?

ColoradoGirl picture ColoradoGirl · May 2, 2014 · Viewed 11.8k times · Source

Ok, I feel this should be extraordinarily simple, but for the life of me I can not figure it out. I'm trying to write a function to find a char in a string for a hangman program. So for I've came up with :

int drawHangman(char trY, string wordA)
{ 
        int wrongTries = 0,            
    if(wordA.find(trY) != string::npos)     //checking to see if char is in word
            wrongTries++;           //if its not, ++
    else
        wrongTries = wrongTries;        //if it is, do wrong tries remains the same
    return wrongTries;                      //return # wrong tries
}

Suggetions?

Answer

Chnossos picture Chnossos · May 2, 2014

You've already found how to check if a character is inside a given string (the find function). Just keep it simple :

bool isInside(const std::string & str, char c)
{
    return str.find(c) != std::string::npos;
}

Try to separate each task into a function that performs one simple thing. The function that finds if a character is in a given string should do nothing more than that. Counting how many times this function returns false is the matter of another function, since this is an unrelated task (unrelated to the search, that is).

Your drawHangman function should just focus on actually drawing the hangman, given through a parameter how many times the user failed, for instance.