这段代码中有一些崩溃错误,我应该找到,但我遇到问题,我已经花了很长时间看。我确信这是我想念的一件容易事。当我在visual studio 2012中运行代码时,我得到了数组下标错误
#include <iostream> // provides access to cin and cout
#include <iomanip>
#include <array>
#include <vector>
using namespace std;
int main()
{
// seed random number generator
srand(time(NULL));
enum symbol
{
Lemon, Cherry, Orange, Bell, Jackpot
};
// create a struct for slot machine wheel
struct Wheel
{
array <string, 10> symbols;
array <symbol, 10> eSymbols;
int position;
string selected;
};
//create an array of three slot machine wheels
array <Wheel, 3> slotMachine =
{
{
{
{"Cherry", "Orange", "Lemon", "Orange", "Bell", "Orange", "Lemon", "Cherry", "Jackpot", "Bell"},
{Cherry, Orange, Lemon, Orange, Bell, Orange, Lemon,Cherry, Jackpot, Bell},
0,"Cherry"
},
{
{"Cherry", "Bell", "Lemon", "Orange", "Bell", "Jackpot", "Lemon", "Cherry", "Jackpot", "Bell"},
{Cherry, Bell, Lemon, Orange, Bell, Jackpot, Lemon, Cherry, Jackpot, Bell},
1,"Bell"
},
{
{"Cherry", "Orange", "Lemon", "Orange", "Lemon", "Orange", "Lemon","Cherry", "Jackpot", "Bell"},
{Cherry, Orange, Lemon, Orange, Lemon, Orange, Lemon, Cherry, Jackpot, Bell},
2,"Lemon"
}
}
};
bool gameOn = true;
bool winner = false;
int thePot = 100;
int bet = 1;
vector <int> combo;
while (gameOn)
{
for (int i = 1; i < 4; i++)
{
slotMachine[i].position =(slotMachine[i].position + rand()%10)%10;
slotMachine[i].selected = slotMachine[i].symbols[slotMachine[i].position];
cout << setw(10) << left << slotMachine[i].selected.c_str() ;
combo.push_back(slotMachine[i].eSymbols[slotMachine[i].position]);
}
if ((combo[0] == combo[1]) && (combo[1] == combo[2]))
{
if (combo[0] == Lemon)
{
cout << "You keep your bet." << endl;
}
else if(combo[0] = Jackpot)
{
cout << "**** You hit $1000 Jackpot!!! ****" << endl;
thePot += 1000;
winner = true;
gameOn = false;
}
else
{
cout << "WINNER! You win $" << combo[0]*5 << endl;
thePot += combo[0]*5;
}
}
else
{
thePot -= bet;
if (thePot > 0 ) gameOn=false;
}
cout << "You now have $" << thePot << endl;
combo.clear();
cout << endl;
cin.get();
}
if (winner) cout << "You walk away a winner." << endl;
else cout << "You have lost all your money." << endl;
// Wait for user input to close program when debugging.
cin.get();
return 0;
答案 0 :(得分:1)
你宣布了一个
array <Wheel, 3> slotMachine;
之后,您按如下方式遍历此数组:
for (int i = 1; i < 4; i++)
{
slotMachine[i].position =
根据循环逻辑,此代码将通过slotMachine[1]
访问slotMachine[3]
。
不幸的是,没有slotMachine[3]
,尝试访问它会导致未定义的行为,并且您可能会崩溃。
N
元素的数组或向量包含从0到N-1
编号的元素。您可以用手指来验证这一事实。
此数组包含slotMachine[0]
到slotMachine[2]
,而不是slotMachine[1]
到slotMachine[3]
。这就是数组和向量在C ++中的工作方式。