c++ - 将字符插入二维字符串时如何不显示空字符?
问题描述
我正在为我的学校项目制作一个非常简单的战舰游戏(我必须使用 Turbo C++),但遇到了问题。我基本上使用 5x5 2D 字符串作为我的板,并在其中隐藏了一个“船”。我想要做的是,每当用户做出错误的猜测时,我想用“X”替换板上的“O”,但是当我这样做时,下一个块中的“O”会被替换通过“/0”并在输出中显示为空格。我该如何解决?
这是代码:
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<stdio.h>
//A function to initialize the board
void start_board(char a[5][5])
{
for(int i=0;i<5;i++)
{ for(int j=0;j<5;j++)
{ strcpy(&a[i][j],"O");
}
}
}
//A function to display the board
void display_board(char a[5][5])
{ for(int i=0;i<5;i++)
{ for(int j=0;j<5;j++)
{ cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
class board
{ public:
char board[5][5];
void start()
{ start_board(board);
}
void display()
{ display_board(board);
}
};
class ship
{ public:
int ship_row, ship_col;
ship()//CONSTRUCTOR FOR PUTTING COORDINATES OF SHIP
{ randomize();
ship_row= random(5);
ship_col=random(5);
cout<<ship_row<<endl<<ship_col;
}
};
class guess: public board, public ship
{ public:
int guess_row,guess_col;
char vboard[5][5];
guess()
{ start_board(vboard);
}
void takeguess();
};
void guess:: takeguess()
{ int count=0;
while(count<3)
{
cout<<endl;
cout<<"Guess a row ";
cin>>guess_row;
cout<<"Guess a column ";
cin>>guess_col;
if(guess_row==ship_row && guess_col==ship_col)
{ cout<<"Congratulations! You sank the battleship!";
break;
}
else if(guess_row>4 || guess_col>4)
{ cout<<"invalid guess";
}
else
{ clrscr();
cout<<"Incorrect Guess!"<<endl;
strcpy(&vboard[guess_row][guess_col],"X");
display_board(vboard);
count+=1;
}
if(count==3)
{ cout<<"GAME OVER!";
}
}
}
void main()
{ clrscr();
board b;
b.start();
b.display();
guess g;
g.takeguess();
getch();
}
例如,如果用户猜测 0,2,而这不是船的位置,输出将显示:
OOX O
OOOOO
OOOOO
OOOOO
OOOOO
很抱歉代码混乱(它不完整)和我在写这篇文章时犯的任何错误,这是我第一次使用 stackoverflow。谢谢您的帮助!
解决方案
不要用strcpy
!!您不是在复制字符串,而是在字符串中设置单个字符的值,因此请使用正确的工具来完成这项工作。
vboard[guess_row][guess_col] = 'X';
这是因为“X”实际上是 2 个字符 'X' 和 '\0' 所以你strcpy
在你的数组中点击了 2 个单元格
推荐阅读
- android - 带有画廊的意图 ACTION.IMAGE.CAPTURE
- java - 如何在mongodb中减去相同索引处的两个数组的元素
- php - 数组仅返回 Laravel 中的第一项
- javascript - 使用不同的投影将 OpenLayers 多边形转换为 GeoJSON
- javascript - 如何排除`ng test --code-coverage`的所有*services.ts?
- django - 在render_field widget_tweaks django中使用Vue attr
- angularjs - Gulp v3.8.8 不会连接控制器文件夹
- scala - Scala 子字符串正确抛出 IndexOutOfBounds 但在 Scala.js 中没有
- javascript - ReferenceError: $tableRows 未定义 jQuery
- yahoo-weather-api - 更新雅虎天气 API - .NET