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

标签 c++ goto

我最近开始学习 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/

相关文章:

javascript - 如果提取的 TXT 不包含某个单词,我如何告诉 imacros 转到某个 url?

c++ - C/C++ : goto into the for loop

c++ - GOTO 还是不 GOTO?

c++ - 为什么 Kdevelop 4 在项目中两次显示我的源 cpp 文件?

c++ - enable_shared_from_this 中的空弱指针

c++ - 在浏览器中使用 C++ DLL

c - Eclipse 转到标签在 C 中不起作用

c - 用于删除 C 代码中所有循环的工具

c++ - 为什么点云库的 loadPCDFile 这么慢?

c++ - 内存引用发送到双指针