首页 > 解决方案 > 将字符插入二维字符串时如何不显示空字符?

问题描述

我正在为我的学校项目制作一个非常简单的战舰游戏(我必须使用 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。谢谢您的帮助!

标签: c++arraysstringmultidimensional-array

解决方案


不要用strcpy!!您不是在复制字符串,而是在字符串中设置单个字符的值,因此请使用正确的工具来完成这项工作。

vboard[guess_row][guess_col] = 'X';

这是因为“X”实际上是 2 个字符 'X' 和 '\0' 所以你strcpy在你的数组中点击了 2 个单元格


推荐阅读