c++ - 带有 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 ;
}
}
}
}
}
解决方案
通常人们会在没有 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 的情况下编写它只是稍微困难一些。不过既然你想用,我就答应了。
推荐阅读
- javascript - 在转换为 typescript 的 create-react-app 项目中,浏览器控制台中丢失的源映射
- css - 如何在引导模式中使用全宽引导网格系统
- sql - ssms 升级而不会丢失数据库凭据
- javascript - React:如何在某些页面上隐藏组件
- php - 从 PHP 生成 SQL 时如何处理 SQL 表名中的特殊字符?
- user-interface - 是否可以将非默认关联作为主要的 KDE 5 Dolphin 右键单击菜单“打开方式”选项?
- c# - RabbitMQ:如何在消费者收到事件的空闲时间后停止通道/连接?
- ios - 在 SwiftUI 中导出文件时显示 ProgressView
- vue.js - v-on="$listeners" 不更新 nuxt/vuejs 中的 v-model
- node.js - Node.js moongoose 转换为 spring mongotemplate