Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

Hangman game - how to do a "wrong guess" in c++?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

apart from that your code is not complete, the actual errors are easy to spot:

  1. You have two loops. The outer "while" loop and the inner "for" loop. Those both use "i" as index, so the inner "i" hides the outer. This is not a bug in itself, but easily leads to other errors, like in your program.

  2. Your second "if", the one that checks for a wrong guess, is outside the "for" loop, which means that the "i" used is the outer one, and not the one you want to use.

  3. The wrong guess code should trigger only if right guess has not. One way to do this is to introduce a helper variable

So with this in mind, it could be rewritten to:

int tries = 0;
while (tries < 999)                                       
    {
        //code
        
        bool guess_wrong = true;
        for (int i = 0; i < mot_secret.length(); i++) // to check each letter
        {
            if (choisi_ton_mot[i] == u_recherche) //guess right
            {
                guess_wrong = false
                mot_secret[i] = u_recherche; // if right change "-" to the right letter
                std::cout << "lettre trouver ! " << std::endl;
            }
        }
        if (guess_wrong)
        {
            std::cout << "rater !" << std::endl;
            faute++;
        }
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...