2014-04-10 129 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