C++ 刽子手游戏-如何做一个;“猜错了”;在c++;?

C++ 刽子手游戏-如何做一个;“猜错了”;在c++;?,c++,C++,我的游戏有效,但不是“错误猜测”部分,“错误”意味着“即使我的猜测是对的,它也会说我错了,或者说我错了好几次,而不是一次” 所以,在我的初学者程序中,这就是我被卡住的地方 char u_recherche; std::string mot_secret(choisi_ton_mot.length(), '-'); std::string choisi_ton_mot; int faute = 0; while (i < 999)

我的游戏有效,但不是“错误猜测”部分,“错误”意味着“即使我的猜测是对的,它也会说我错了,或者说我错了好几次,而不是一次”

所以,在我的初学者程序中,这就是我被卡住的地方

char u_recherche;  
std::string mot_secret(choisi_ton_mot.length(), '-');  
std::string choisi_ton_mot;  
int faute = 0;

 while (i < 999)                                       
    {
        //code

        for (int i = 0; i < mot_secret.length(); i++) // to check each letter
        {
            if (choisi_ton_mot[i] == u_recherche) //guess right
            {
                mot_secret[i] = u_recherche; // if right change "-" to the right letter
                std::cout << "lettre trouver ! " << std::endl;
            }
        }
        if (choisi_ton_mot[i] != u_recherche) //guess wrong
        {
            std::cout << "rater !" << std::endl;
            faute++;
        }
charu\u recherche;
std::string mot_secret(choisi_ton_mot.length(),'-');
std::字符串choisi_tonu_mot;
内部故障=0;
而(i<999)
{
//代码
用于(int i=0;istd::cout除了代码不完整之外,实际错误很容易发现:

  • 您有两个循环。外部的“while”循环和内部的“for”循环。这两个循环都使用“i”作为索引,因此内部的“i”隐藏外部。这本身不是一个bug,但很容易导致其他错误,就像在您的程序中一样

  • 你的第二个“如果”,即检查错误猜测的那个,在“for”循环之外,这意味着使用的“i”是外部的,而不是你想要使用的

  • 只有在正确的猜测没有触发时,才会触发错误的猜测代码。一种方法是引入一个helper变量

  • 因此,考虑到这一点,可以将其改写为:

    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++;
            }
    ...
    
    int=0;
    while(尝试<999)
    {
    //代码
    布尔猜错了=真;
    用于(int i=0;istd::难道发布的代码不能编译,至少部分原因是它不完整。请给我们更多的细节或至少更多的代码。也许你的第二个if语句也应该在for循环中?同样,我只能建议在编码时使用英语。谢谢你的帮助,我的问题问得很糟糕,我很高兴你接受了是时候帮我了,我应该删除这个问题,如果我删除了,我就不会感谢你了