Detecting a letter within and on the back and front of something

closed account (367kGNh0)
I am aware of the syntax

1
2
3
4
5
6
7
XYZ.front()

//and

XYZ.back()

// I am unaware of how to detect a character in the midst of a word, like the 'a' in 'rain' 


I imagine if making a hangman game these would be used to cause changes to the underscores, if so, how do you implement them. Here are three examples I would appreciate an answer to, so I know how to detect letters within words

EG.1) a person guesses the 's' in 'school' so it displays s__oo_ (he/she already guessed the 'o's)


EG.2) a person guesses the 'e' in 'bridge' so it displays _____e


EG.3) a person guesses the 'i' in 'stair' so it displays ___i_
Last edited on
Just use a for loop to compare the target characters one-by-one with the latest guess. If there is a match, change the underscore in the shown string to the relevant character and set a boolean variable to true to indicate at least one success.

Be careful with upper-case/lower-case alternatives.

Something like this might give you some ideas:

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
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <cctype>   // tolower

using namespace std;

int main()
{
string theWord="testing";
string theDisp (theWord.length(),'.');
char guess;

cout << "Word to Guess:\t" << theWord << endl; 

    do{
    cout << "Enter Letter:\t";
    cin >> guess;
    guess=tolower(guess);

    cout << "The Guess:\t" << guess << endl;

    std::size_t found = theWord.find_first_of(guess);
    while (found!=std::string::npos)
    {
    theDisp[found]=guess;
    found=theWord.find_first_of(guess,found+1);
    }

    cout << "Revealed ...:\t" << theDisp << endl;
    }
    while(theWord != theDisp);

return 0;
}


This is in no way meant to be perfect, or necessarily the best way of doing things ... it's just a way. If you find it useful, then great.
closed account (367kGNh0)
sorry for the late reply, but great! I can work far with this!
Topic archived. No new replies allowed.