gpt4 book ai didi

c++ - Goto 无法正常工作 C++

转载 作者:行者123 更新时间:2023-11-27 23:04:08 25 4
gpt4 key购买 nike

我最近开始学习 c++,我只是通过制作一个糟糕的小游戏来测试我所知道的。

我想跳回我的代码,所以我了解了 goto 语句。这是我的代码(不是全部,只是 goto 位)

moving:

if(moveChoice == "Forward"){
cout << "You moved Forward" << endl;
moveChoice = "";
if(firstTargetRand == 2){
cout << "You encountered a tree!" << endl;
}if(firstTargetRand != 2){
cout << "goto init" << endl;
goto moving;
}
}

现在正在调用“goto moving”(使用 cout goto init 检查),但这不起作用。我知道这可能是一个非常愚蠢的错误,但我看不出有什么问题

最佳答案

好吧,首先,我觉得有义务提及 goto 几乎不被用于任何用途,并且正如评论所说,这是主要循环 Material 。

你的问题是你正在检查 moveChoice == "Forward",然后将 moveChoice 设置为 "",然后返回,然后 moveChoice == "Forward"总是返回 0。

如果你真的想要 goto,试试这个:

if(moveChoice == "Forward"){
moving:
cout << "You moved Forward" << endl;
moveChoice = "";
if(firstTargetRand == 2){
cout << "You encountered a tree!" << endl;
}else{
cout << "goto init" << endl;
goto moving;
}
}

如果你不是特别偏爱 goto,试试这个:

while(moveChoice=="Forward"){
cout << "You moved Forward" << end1;
if(firstTargetRand == 2){
cout << "You encountered a tree!" << end1;
moveChoice = "";
}else{
cout << "goto init" << end1;
}
}

关于c++ - Goto 无法正常工作 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24744103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com