I started c++ a few weeks ago and I have been having trouble with this for a few days now. I am trying to make a minesweeper game as you see below. At the moment i am just trying to print out the board/minefield. For some reason it will go through the nested for loop a few times the crash, sometimes it will make it though the whole program to "END" and then crash, but most of the time it only lasts a few lines. I have no idea what the problem is so any help would be appreciated. Thanks.
#include <iostream>
#include <cstdlib> // include things
#include <ctime>
usingnamespace std;
int main() // MINESWEEPER text based - input a co-ord in order to click a square just like normal minus the mouse
{ // eg "input a co ordinate"
// 3 4 == [3][4]
// -----------
// | 1X1 | <--- somewhat like that where X = bomb
// | 111 |
int b[8][8]; //declare array for board
srand ( (unsignedint)time(NULL) );
int bombs = 0; // control no of bombs
int temp = 1; // temp number for making board
while ( bombs < 8 ) // sets up the minimum number of mobs on the board at once
{
cout << "START" << endl;
int cx = 0; // x and y co-ords for the bombs location (b array)
int cy = 0;
bombs = 0; // setting bombs to zero
for(int ctl = 0; ctl < 8; ctl += 1) //defining the minesweeper board [8*8]
{
for(int cnt = 0; cnt < 8; cnt += 1)
{
temp = rand() % 6; // temp = random number between 0 and 5
if ( temp < 1 ) // if temp == 0
{
b[cx][cy] = 1; // then theres a bomb on [cx]cy]
}
if ( temp > 0 )
{
b[cx][cy] = 0; //if temp != 0 then no bomb on [cx][cy]
}
cout << b[cx][cy]; // print [cx][cy] for testing purposes
if (b[cx][cy] == 1) // if theres a bomb on [cx][cy]
{
bombs += 1; // add one o the counter
}
cx += 1; // repeat for the rest of the line
// cout << endl;
}
cy += 1; // repeat for the next line and so on
cout << endl;
} // breaks out of loop if theres enough bombs
}
cout<< "END"; //the end (so far)
}
You're subscripting out of bounds. In your loop from 27-47, you're incrementing cx for each pass of the loop. When you go to the next iteration of the outer loop (25-50), you continue to increment cx. Eventually, cx goes out of bounds. You probably wanted to set cx to 0 at line 26.