【问题标题】:C++: How do I assign an object within an array based on user input?C++:如何根据用户输入在数组中分配对象?
【发布时间】:2016-10-31 23:16:35
【问题描述】:

这里我有一个代理数组,我想初始化一个玩家数组。代理人只有他的名字。用户必须输入球员姓名、球衣号码和球员经纪人。在这种情况下,我希望多个玩家能够拥有相同的代理,因此我使用了指针。

// Default constructor = Agent(std::string = "")
Agent agents[2] = {"Larry", "Joe"};

// Default constructor = Player(std::string = "", int = 0, Agent* = 0)
Player players[3];
initializePlayers(players, 3);

void initializePlayers(Player players[], int playerSize)
{
    string playerName, agentName;
    int playerNum;
    Agent *myAgent;

    for(int i = 0; i < playerSize; i++)
    {
        cout << "Please enter the player's name: ";
        getline(cin, playerName);

        cout << "Please enter the player's number: ";
        cin >> playerNum;

        cout << "Please enter the player's agent: ";
        getline(cin, agentName);
        cin.ignore(1000, '\n');

        // If the agent's name matches one of the names in agents array
        // assign that agent to this player

        Player tempPlayer(playerName, playerNum, myAgent);
        players[i] = tempPlayer;
    }
}

在我的 cmets 中,我需要分配 myAgent。例如,如果用户为第一个玩家输入“Larry”,Larry 应该是他的代理人。如果用户为接下来的两个玩家输入“Joe”,那么他们都应该让 Joe 作为他们的代理。我该如何做到这一点?即使是让我开始的想法也会有所帮助。谢谢。

【问题讨论】:

  • 使用循环搜索正确的代理。一旦找到,分配它。故事结束。
  • 或者使用string->Agent的映射
  • 这与您的问题无关,但请参阅stackoverflow.com/questions/10553597/…。否则你会得到错误的 agentName 值。

标签: c++ arrays pointers


【解决方案1】:

首先你最好使用std::array 这样的:

// Default constructor = Agent(std::string = "")
std::array<Agent, 2> agents = { Agent("Larry"), Agent("Joe") };

然后你可以这样搜索代理:

myAgent = nullptr;
for (unsigned i = 0; i < agents.size(); ++i)
{
    if (agentName == agents.getName())
      myAgent = &agents[i];
}

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2021-09-24
    • 2020-11-17
    • 2021-10-14
    • 2021-11-18
    • 2017-09-11
    • 2011-11-08
    • 1970-01-01
    • 2014-05-05
    相关资源
    最近更新 更多