转到一个新块

C++ Go to a new block?

本文关键字:一个 新块      更新时间:2023-10-16

我是一个完全的c++新手,如果这是可能的,我想从int main()切换到int game(),我不确定这是否完全可能。

    #include <iostream>
#include <cstdlib>
using namespace std;
string name;

int main()
{
    //So this is where we get the users name.
    string namechoice;
    cout << "Hello adventurer." << endl;
    cout << "What is your name?n";
    cout << "n";
    cout << "n";
    cout << "n";
    cout << "n";
    cout << "                               Name: ";
    cin >> name;
    system("CLS");
    cout << "So your name is " << name << ", Correct? (Y / N)n";
    cin >> namechoice;
    namechoice[0] = toupper(namechoice[0]);
    system("CLS");
    if (namechoice == "Y"){
    }
    else if (namechoice == "N"){
        while(namechoice == "N"){
            cout << "Please enter your name: ";
            cin >> name;
            system("CLS");
            cout << "You're name is " << name << ", Correct? (Y / N)n";
            cin >> namechoice;
            namechoice[0] = toupper(namechoice[0]);
            system("CLS");

        }
    }
}
int game()
{
        cout << "Test";
        return 0;
}

那么我要问的是,如果我在int main中的任何一个条件最终都满足了,我如何去int game()。

提前感谢!

game();去你想去的地方。它将调用相应的函数,将控制权转移给它。虽然如果你想在main之后保留game函数,你需要在main之前像int game();一样的前向声明,这样main就知道它是什么样子的,以及如何调用它。

例如:

int game(); // forward declaration
int main() {
    if (condition) {
        // calling a function transfers control to it.
        int result = game();
        // After its return, the flow continues from where we _stopped_.
        // You can print game's result, if you wish.
        cout << result << "n";
    } else {
        // do something else
    }
    return 0;
}
int game() {
    cout << "Testn";
    // _return_ will "terminate" this function's flow and return control back
    // to the caller function.
    return 0; // This value will be returned to the caller function.
}

您需要添加#include <sstream>来输入字符串!你可以在任何地方添加游戏功能,它将在扫描的线上被调用。另外一个很好的做法是在底部添加main函数,以及使用void关键字。下面是我的例子:

void game(){
       cout<<"Test";
    }
int main(){
       game();
return 0;
    }