如何识别C++ while循环中的最后一次迭代?

ton*_*ony 6 c++

我如何制作,以便最后一个玩家名称没有,这样的:

Player online:
Jim, John, Tony
Run Code Online (Sandbox Code Playgroud)

并不是

Player online:
Jim, John, Tony,
Run Code Online (Sandbox Code Playgroud)

我的代码是:

bool Commands::whoIsOnline(Creature* c, const std::string &cmd, const std::string &param)
{
Player* player = dynamic_cast<Player*>(c);

if (player)
{
    player->sendTextMessage(MSG_STATUS_CONSOLE_BLUE, "Players online: ");
    AutoList<Player>::listiterator iter = Player::listPlayer.list.begin();
    std::string info;
    int count = 0;

    while (iter != Player::listPlayer.list.end())
    {
        info += (*iter).second->getName() + ", ";
        ++iter;
        ++count;

        if (count % 10 == 0)
        {
            player->sendTextMessage(MSG_STATUS_CONSOLE_BLUE, info.c_str());
            info.clear();
        }
    }

    if (!info.empty())
        player->sendTextMessage(MSG_STATUS_CONSOLE_BLUE, info.c_str());
}

return true;
}
Run Code Online (Sandbox Code Playgroud)

Pon*_*dle 7

而不是像player + ","想象它那样思考"," + player

所以你可以做这样的事情(伪代码):

onFirstName = true
output = ""
for each player in players:
    if onFirstName:
        onFirstName = false
    else:
        output += ", "
    output += player's name
Run Code Online (Sandbox Code Playgroud)

如果你的语言支持它(c ++做什么):

if length of players > 0:
    output = players[0]
    for each player in players except players[0]:
        output += ", " + player's name
else:
    output = ""
Run Code Online (Sandbox Code Playgroud)

我喜欢最后一个的外观,我必须发明一种实际上就是这样的语言.


Mar*_*iot 4

改变

while(iter != Player::listPlayer.list.end())
{
    info += (*iter).second->getName() + ", ";
//...
Run Code Online (Sandbox Code Playgroud)

和:

if(iter != Player::listPlayer.list.end()){
    info += (*iter).second->getName();
    ++iter;
    while(iter != Player::listPlayer.list.end()){
    {
        info += ", " + (*iter).second->getName();     
        //...
    }
    //...
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您不希望 info.clear() 之后的名称前面有逗号,则可以执行以下操作:

while(iter != Player::listPlayer.list.end())
{
    info += ", " + (*iter).second->getName();
    // ...
        player->sendTextMessage(MSG_STATUS_CONSOLE_BLUE, info.c_str()+2);
Run Code Online (Sandbox Code Playgroud)

  • 我会使用这种方法,但使 while 循环从属于 if 语句。如果 if 没有成功,那么 while 的第一个测试就不可能成功。 (2认同)