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++;
}
}
我在写一个战舰游戏。我有电路板布局工作,计算机随机生成船只。现在我正在研究这种方法来提示用户输入船只的坐标当我运行程序时,它允许我输入5艘船。当我进入第6艘船时,它给了我这个错误。
变量位置周围的堆栈已损坏。
我在网上寻找答案,但没有找到任何独家的答案。
任何帮助都将不胜感激。
答案 0 :(得分:12)
location
是一个char
的数组
没有location[1]
。
答案 1 :(得分:6)
您正在向您的用户提示location
阵列的内存地址。您应该分别询问位置索引:
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++;
}
}
注意int location[2];
,因为大小为1的数组只能容纳一个元素。我还将元素类型更改为int。从控制台读取字符将导致ASCII值,这可能不是您想要的。
答案 2 :(得分:3)
您使location
变量只能容纳一个字符。您可以访问它,期望它至少保存2个字符。如果您正在使用cin并期望读取两个字符,那么更好的方法是:
char locationX, locationY;
// ...
std::cin >> locationX >> locationY;
// ...
Grid[locationX][locationY] = SHIP;
答案 3 :(得分:3)
cin >> location;
location
是一个char
的数组。这不能成功,因为当您从流中读取char
数组时,必须添加一个空终止符(需要一个字符)。你将不可避免地超出数组的界限。
您可以使用std::string
,它可以帮助您避免任何缓冲区溢出问题:
std::string location;
if (!(std::cin >> location)) {
// handle input error
}
另请注意,您可能需要将数字的字符串表示形式转换为数字值。您可以通过从流中读取两个int
对象来轻松完成此操作:
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