2014-04-10 135 views
0

在這段代碼中,我使用了一個整數數組,因爲我覺得如果它們是整數,我工作的項目將會更加容易。在這個數組中,我將每個位置指定爲46(ASCII代表'。')並打印出該ASCII的(char)版本。我之所以讓董事會整體上的原因是因爲我會在這個委員會上發佈數字,但我想維護'。'我打印。如何在C++中的字符數組中打印字符

電流輸出:

. . . . . 

    . . . . . 

    . . . . . 

    . . . . . 

    ☺ . . . . 

所需的輸出:

. . . . . 

    . . . . . 

    . . . . . 

    . . . . . 

    1 . . . . 

與(炭)鑄造將打印 '' (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); 
    } 
+0

假設我在做類似2048遊戲字符數組將不能持有超過8大數目,所以我將使用一個int數組 – user3517150

回答

0

你爲什麼不使用字符數組?我覺得它會更容易。

,如果我能

0

的數字1 ASCII碼數是49我會發表評論。如果您想打印數字1,則必須發送ascii值49。該數字是爲了開始48 0

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

因此,你可以再補充48到你的任何數字。這將只適用於單個數字。

我會建議你使用一個char數組,因爲你可以看到這個變得複雜,收益不大。

檢查這個ascii表here

+0

假設我在做類似的遊戲,以2048的char數組將不能保存大於8的數字,所以我將使用int數組 – user3517150

+0

在這種情況下,您應該使用一個ints數組,但是,您應該只輸出「cout」流而不是轉換他們對人物。如果你想在某些情況下打印點,比如值爲0,只要做一個if語句併發送'。'。當int是0時流到流。 –

0

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

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

見的可打印字符的十進制值的ascii chart