C++ 如何在二维字符串中插入字符时不显示空字符?
我正在为我的学校项目制作一个非常简单的战舰游戏(我必须使用Turbo C++),我遇到了一个问题。我基本上使用5x5 2D字符串作为我的棋盘,并在其中隐藏“船”。我想做的是,每当用户做出错误猜测时,我想用“X”替换电路板中的“O”,但当我这样做时,下一个块中的“O”会被替换为“/0”,并在输出中显示为空白。我该如何解决这个问题 代码如下:C++ 如何在二维字符串中插入字符时不显示空字符?,c++,arrays,string,multidimensional-array,C++,Arrays,String,Multidimensional Array,我正在为我的学校项目制作一个非常简单的战舰游戏(我必须使用Turbo C++),我遇到了一个问题。我基本上使用5x5 2D字符串作为我的棋盘,并在其中隐藏“船”。我想做的是,每当用户做出错误猜测时,我想用“X”替换电路板中的“O”,但当我这样做时,下一个块中的“O”会被替换为“/0”,并在输出中显示为空白。我该如何解决这个问题 代码如下: #include<conio.h> #include<iostream.h> #include<stdlib.h> #in
#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();
}
很抱歉,我在写这篇文章时,代码凌乱(不完整)并且犯了错误,这是我第一次使用stackoverflow。谢谢你的帮助 不要使用strcpy!!您不是在复制字符串,而是在设置字符串中单个字符的值,因此请使用正确的工具执行此任务
vboard[guess_row][guess_col] = 'X';
这是因为“X”实际上是两个字符“X”和“\0”,所以您的strcpy
命中数组中的两个单元格
vboard[guess_row][guess_col] = 'X';