gpt4 book ai didi

c++ - 如何在一个函数中拥有所有选项?

转载 作者:行者123 更新时间:2023-11-28 04:03:47 25 4
gpt4 key购买 nike

所以我正在制作一个文字冒险游戏,我希望能够拥有一个包含所有输入的功能。因此,我不必每次都创建一个 if 语句来检查每个方向,我可以只放置一个包含所有这些的函数。我该怎么做?

    string input;
while (input != "n", "s", "e", "w")
{
getline(cin, input);
if (input == "n")
{
dTable();
}
if (input == "e")
{
cout << "You sit on the sofa. Congratulations" << endl;
}
if (input == "w")
{
cout << "You just ran into a wall" << endl;
}
if (input == "s")
{
outsideHouse();
}
if (input == "stats")
{
stats();
}
if (input == "help")
{
help();
}
else
{
cout << "Sorry I am not Siri I don't understand" << endl;
getline(cin, input);
}
break;
}

return 0;
}

最佳答案

您可以在这里看到使用函数的不同方法,这就是我将如何解决这个问题。您可以专注于在 main() 部分添加新问题而不必编写所有的 if 请求一遍又一遍。

    #include <iostream>
#include <string>

using namespace std;

void help();
void stats();

string check(string input,string n,string s, string w, string e)
{
string result;
if (input == "n"){
result = n;}

else if (input == "s"){
result = s;}

else if (input == "w"){
result = w;}

else if (input == "e"){
result = e;}

else if (input == "help"){
cout << "help" << endl;} //help()

else if (input == "stats"){
cout << "stats" << endl;} // stats()

else if (input == "exit"){
result = "exit";}

else
cout << "Sorry I am not Siri I don't understand. Try again" << endl;


return result;
}

string call()
{
string input;
cout << "Where do you want to go? n s w e" << endl;
getline(cin, input);
return input;
}

int main()
{
bool slope = false;
string input, result;

input = call();
result = check(input,"outside","dTable", "You just ran into a wall", "You sit on the sofa. Congratulations");

while (slope != true)
{

if(result == "house")//room1
{
cout << "You are in the house" << endl;
input = call();
result = check(input,"outside","dTable", "You just ran into a wall", "You sit on the sofa. Congratulations");
}
else if(result == "outside")//room2
{
cout << "You are outside"<< endl;
input = call();
result = check(input,"You just ran into a wall", "house","dTable", "You sit on the sofa. Congratulations");
}
else if(result == "dTable")//room3
{
cout << "You are dTable" << endl;
input = call();
result = check(input,"You just ran into a wall", "You sit on the sofa. Congratulations","outside","house");
} ///adding one room after another and connect it with each other
else if(result == "exit")
{
slope = true;
}
else
{
cout << result << endl;
input = call();
//some winning or loosing message here
}
}
return 0;
}

关于c++ - 如何在一个函数中拥有所有选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078988/

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