簡體   English   中英

如何在C ++中的char數組中打印字符

[英]how to print characters in a char array in C++

在這段代碼中,我使用了一個整數數組,因為如果它們是整數,我覺得我正在從事的項目會容易得多。 在此數組中,我將每個位置分配給46(“。”為ASCII),並打印出該ASCII的(字符)版本。 我將板子設置為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);
  }

為什么不使用char數組? 我覺得這會容易些。

如果可以的話我會發表評論

數字1的數字為49 如果要打印數字1 ,則必須發送ascii值49 這些數字從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表。

只需將48加到您的值即可。

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

有關可打印字符的十進制值,請參見ascii圖表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM