【问题标题】:how to print characters in a char array in C++如何在 C++ 中打印字符数组中的字符
【发布时间】:2014-04-10 01:37:01
【问题描述】:

在这段代码中,我使用了一个整数数组,因为我觉得如果它们是整数,我正在处理的项目会容易得多。在这个数组中,我将每个位置分配给 46(ASCII 表示 '.')并打印出该 ASCII 的 (char) 版本。我将板子设置为 int 的原因是因为我将在此板上放置数字,但我想保持“。”我打印的。

电流输出:

  .   .   .   .   .

  .   .   .   .   .

  .   .   .   .   .

  .   .   .   .   .

  ☺   .   .   .   .

期望的输出:

  .   .   .   .   .

  .   .   .   .   .

  .   .   .   .   .

  .   .   .   .   .

  1   .   .   .   .

使用 (char) 进行强制转换将打印 '.' (ASCII 46)很好,但我的数字会被扭曲,正如当前输出所指示的那样。

我该如何解决这个问题?我一直盯着这个看。

我的代码:

using namespace std;
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <math.h>


void addRandomNumberToBoard(int *board, int &arrSize)
  {
  srand ((int)time(0)); //seed random

  int destination;

  do destination= rand() % (arrSize-1);

  while ( board[destination] != '.'); // place on a random spot on the board

  int randomNumber=rand() < RAND_MAX / 2 ? 1 : 2; //generate number 1 or 2
  board[ destination] = randomNumber;  //place the number there
  }

int printBoard(int &i, int &arrSize, int *board)
  {

  for(i=0; i<arrSize; i++)
      {
      if( i % 5 == 0 && i!=0) //after every 5 positions print a new line
        cout<<"\n\n";
      cout<<"   "<<(char)board[i]; //this MIGHT be the problem
      }
  }



int main()
  {
  int i;
  int arrSize=25;
  int board[arrSize];

  for(i=0; i<arrSize; i++) //declare all positions as ASCII '.'
    board[i]='.'; //this MIGHT be the other problem

  addRandomNumberToBoard(board,arrSize);
  printBoard(i, arrSize, board);
  }

【问题讨论】:

  • 假设我正在制作一个类似于 2048 的游戏。char 数组将无法容纳大于 8 的数字,所以我将使用 int 数组

标签: c++ arrays integer character


【解决方案1】:

为什么不使用 char 数组?我觉得这样会更容易。

如果可以的话,我会发表评论

【讨论】:

    【解决方案2】:

    数字1 的ASCII 码是49。如果要打印数字1,则必须发送49 的ascii 值。 0 的数字从 48 开始按顺序排列:

    0 - 48
    1 - 49
    2 - 50
    3 - 51
    4 - 52
    5 - 53
    6 - 54
    7 - 55
    8 - 56
    9 - 57
    

    因此,您只需将 48 添加到您的任何数字。但是,这仅适用于个位数。

    我建议您使用 char 数组,因为您可以看到这会变得很复杂而收效甚微。

    检查这个 ascii 表here

    【讨论】:

    • 假设我正在制作一个类似于 2048 的游戏。char 数组将无法容纳大于 8 的数字,所以我将使用 int 数组
    • 在这种情况下,您应该使用整数数组,但是,您应该只在cout 流上输出,而不是将它们转换为字符。如果您想在某些情况下打印点,例如值是否为 0,只需创建一个 if 语句并发送一个 '.'当 int 为 0 时发送到流。
    【解决方案3】:

    只需将 48 添加到您的值。即

    board[destination] = randomNumber + 48; // Ascii 49 is '1', 50 is '2'.
    

    有关可打印字符的十进制值,请参阅ascii chart

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 2021-09-21
      • 1970-01-01
      • 2023-03-07
      • 2012-07-26
      • 2014-12-21
      • 2015-12-13
      • 1970-01-01
      相关资源
      最近更新 更多