void GameBoard::enterShips()
{
char location[1];
int ships = 0;
int count = 1;
while(ships < NUM_SHIPS)
{
cout << "Enter a location for Ship " << count << ": ";
cin >> location;
cout << endl;
Grid[location[0]][location[1]] = SHIP;
ships++;
count++;
}
}
Im writing a battleship game. I have the board layouts working and the computers randomly generated ships. Now I am working on this method to prompt the user to enter coordinates for the ships When I run the program, it allows me to enter 5 ships. When I enter the 6th ship, it gives me this error.
Stack around the variable location was corrupted.
Ive looked for answers online and have not found anything exclusive.
Any help would be appreciated.
location
is an array of a single char
.
There is no location[1]
.
You are prompting the memory address of location
array to your user. You should ask location indices separately:
void GameBoard::enterShips()
{
int location[2];
int ships = 0;
int count = 1;
while(ships < NUM_SHIPS)
{
cout << "Enter a location for Ship " << count << ": ";
cin >> location[0];
cin >> location[1];
cout << endl;
Grid[location[0]][location[1]] = SHIP;
ships++;
count++;
}
}
Notice int location[2];
since an array of size 1 can only hold one element. I also changed the element type to int. Reading char's from the console will result in ASCII values, which are probably not what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With