首页 > 解决方案 > 带有 for 循环的 goto() 函数

问题描述

我正在制作一个简单的猜谜游戏,用户必须猜测隐藏地图(数组)中的一个键位置,他有 12 次尝试做出他的猜测,我几乎成功了,但唯一的问题是计数器不是更改我希望TryCounter当用户不猜测密钥的位置时实际计算尝试次数这是我的代码:

#include <iostream> 
using namespace std;

int main()
{
    bool w;
    int x;
    int y;
    
    int array1[6][6] = {0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0};
    cout << "game is starting ... " << endl;
    cout << "You have 12 try to find one of the hidden keys " << endl;
    loop: for (int TryCounter = 1; TryCounter <= 12; TryCounter++)
    {
        cout << " guess  " << TryCounter << "  - x and -y coordiants : " << endl;
        cin >> x;
        cin >> y;
         if (TryCounter == 12)
        {
            cout << "You have used your chances" << endl;
            if (w == false)
            {
                cout << "You lost" << endl;
                for (int i = 0; i < 6; i++)//Drawing the hidden array
                {
                    cout << "   " << endl;
                    for (int j = 0; j < 6; j++)
                    {
                        cout << array1[i][j];
                        cout << "   ";  
                    }
                }break;
            }break;
    }
        for (int i = 0; i < 6; i++)//checking the input
        {
            for (int j = 0; j < 6; j++)
            {
                if (array1[x][y] == 1)
                {
                    cout << "" << endl;
                    cout << "--- Nice Shot ! ---" << endl;
                    w = true;
                    cout << "You Won" << endl;
                    for (int i = 0; i < 6; i++) //drwaing the hidden map
                    {
                        cout << "   " << endl;
                        for (int j = 0; j < 6; j++)
                        {
                            cout << array1[i][j];
                            cout << "   ";
                        }
                    }return 0;
                }
                else if (array1[x][y] == 0) //wrong guess
                {
                    w = false;
                    cout << "--- You missed ---" << endl;
                    goto loop ;
                }
            }
        } 
    }

}
 

标签: c++arraysloops

解决方案


通常人们会在没有 goto 的情况下努力编程。但有时它确实有用......所以这里不做判断。

int main(...) {
   // the variable and array stuff...
   for(int attemptCounter = 0; attemptCounter < 12; ++attemptCounter) {
      // the user input stuff...
      // the checking if user guessed right
      if( userGuessedCorrectly ) goto Success;
   }
   std::cout << "better luck next time, pal - you did not guess right." << std::endl;
   return 0;
Success:
   std::cout << "Congratulations you made it!" << std::endl;
   return 0;

}

当然,在没有 goto 的情况下编写它只是稍微困难一些。不过既然你想用,我就答应了。


推荐阅读