使用数组条件中断循环

时间:2017-10-25 04:23:19

标签: c++ arrays loops for-loop if-statement

我目前正在为课堂制作一个Chutes and Ladders游戏。这场比赛的胜利条件是如果一名球员登上Square 100,他们就赢了。如果他们碰巧超过100,他们就会待在那里,直到每个人都完成游戏(要么有人登陆100,要么每个人都超过100)。如果每个人都超过100,我就无法摆脱while循环。

有很多代码,所以我会尽可能简化。在!!!这里是问题!!!!是我需要帮助的地方。

有没有办法指定一次数组中的所有元素都超过100才能中断?对不起,如果问题是重复...这篇文章有更详细的内容。

string name[MAXplayers]; //Array to store names
int position[MAXplayers]; //Array to store board position

unsigned seed; //Random Number Generator Seed
seed = time(0); //Set seed to 0
srand(seed); //Call srand function

int spin;
bool done = false;
int counter = 0;
const int WIN = 100;

while (done != true)
{
    if (counter == WIN)
    {
        cout << "That's it, game over!" << endl << endl;
        done = true;
    }
    else 
    {
        for (int i = 0; i < players; i++)
        {
            if (position[i] > WIN) //!!!!!HERE IS THE PROBLEM!!!!!!
            {
                cout << "Sorry " << name[i] << "! You can't move! You're stuck at " << position[i] << endl << endl;
            }
            else
            {
                cout << name[i] << "'s turn! Pres [Enter] to spin the wheel!";
                cin.get();
                spin = rand() % 12 + 1;
                cout << "You spun the number " << spin << "!" << endl;

                int temploc = position[i] += spin;
etc...etc...etc...etc...etc...etc...

1 个答案:

答案 0 :(得分:0)

要在符合WIN条件时跳出for循环,您可以使用关键字 break 。无论for循环的条件如何,这都将停止循环处理。

但请注意,在发布后,程序仍会围绕while循环进行迭代,直到满足条件done != true为止。