void GameBoard::enterShips()
{
char location[1];
int ships = 0;
int count = 1;
while(ships < NUM_SHIPS)
{
cout << \"Enter a loc
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.
You made the location
variable only able to hold a single character. You access it expecting it to hold at least 2 characters. If you're using cin and expecting to read exactly two characters, a better method would be:
char locationX, locationY;
// ...
std::cin >> locationX >> locationY;
// ...
Grid[locationX][locationY] = SHIP;
cin >> location;
location
is an array of one char
. This can't succeed because when you read from a stream into a char
array, a null terminator has to be added (which takes one character). You will inevitably overrun the bounds of the array.
You can use a std::string
, which will help you avoid any buffer overrun issues:
std::string location;
if (!(std::cin >> location)) {
// handle input error
}
Note also that you probably need to convert the string representations of the numbers into numeric values. You can easily do this by reading from the stream into two int
objects instead:
int x_location, y_location;
if (!(std::cin >> x_location >> y_location)) {
// Handle input error
}
if (x_location >= X_DIMENSION || x_location < 0 ||
y_location >= Y_DIMENSION || y_location < 0) {
// Handle out-of-range error
}
// use x_location and y_location