将字符串操作为变量名称?

时间:2013-02-01 18:55:40

标签: c++ naming-conventions

我是编程新手,我的代码有些问题: 我不太确定那个东西是怎么调用的,所以很难谷歌呢; 但我认为人类会理解我的意思:

while循环每次增加i ++。在评论栏中我想表达

当 i = 1,player1.cards [j] =随机; i = 2,player2.cards [j] = random;

void cardScramble()
{
  int random;
  int i = 1;
  while (i <= 4)
  {
    cout << "Card of Player " << i << " : ";
    int j = 0;
    while (j < 13)
    {
      random = rand() % 52;
      if (cards[random] == NULL)
      {
        cards[random] = i;
        cout << cardName(random) << " , ";
        /*   player(i).cards[j] = random; */
        /* That's what I'm doubt with */
        j++;
      }
    }

    cout << endl;
    i++;
  }
  return;
}

我尝试定义它或将其作为字符串操作但不起作用。 有人可以帮我吗?非常感谢!

2 个答案:

答案 0 :(得分:4)

你不能按照你的想法去做。相反,将player1player2(以及任何其他玩家)合并到一个数组中。例如:

Player_Type player[2]; // alternatively std::array<Player_Type,2> player;

然后你可以使用i来引用每个玩家:

player[i].cards[j] = random;

或者,如果你想从1开始i,那么只需从中减去1:

player[i-1].cards[j] = random;

答案 1 :(得分:1)

您可以使用如下所述。你需要一个带有int数组的结构。

 struct Player
    {
        public
        int[] cards = new int[13];
    }; 

然后你的while循环就像下面那样

Palyer []player = new Palyer[4];

int random;
        int i = 1;
        while (i <= 4)
        {
            cout << "Card of Player " << i << " : ";
            int j = 0;
            while (j < 13)
            {
                random = rand() % 52;
                if (player[i].cards[random] == NULL)
                {
                    cards[random] = i;
                    cout << cardName(random) << " , ";
                     player[i].cards[j] = random; 
                    /* That's what I'm doubt with */
                    j++;
                }
            }
            i++;
        }

//如果有帮助,请回答