2016-04-24 195 views
1
ref void init_board (ref int side, ref char[][] board) //make empty symbol chessboard 
{ 
    const char black = ' '; 
    const char white = 0xB0; 

    board[0][0] = ' '; 
    for (int i = 1; i <= side; i++) 
    { 
     board[i][0] = 0x30 + i; //Setting nums; "Error: Cannot convert int to char" 
     board[0][i] = 0x40 + i; //Setting letters; same here 
     for (int j = 1; j <= side; j++) 
      board[i][j] = (i+j)%2 == 0 ? black : white; //making black-white board 
    } 
} 

我想做一個簡單的象徵棋盤。如何正確設置數字和字母取決於或行數/列數? board[i][0] = 0x30 + i;(或0x40的)工作在C++,但不是在D.將int轉換爲char?

+0

是什麼'裁判void'嗎? – sigod

+0

@Kerbiter你爲什麼在那裏使用ref?在任何一方面? 'ref int'當它只被讀取時是一個完全的浪費,'ref char [] []'同樣只是在這裏增加了另一個間接的方法。 –

回答

6

你已經有了你需要的std.conv模塊。 - 最好的是使用std.conv.to

import std.conv; 
import std.stdio; 

void main() { 
    int i = 68; 
    char a = to!char(i); 
    writeln(a); 
} 

輸出:

D 
1
board[i][0] = cast(char)(0x30 + i); 

請記住,轉換這樣的時候,它可能溢出。

+0

謝謝,會嘗試。 – Kerbiter

+3

使用['std.conv.to'](http://dlang.org/phobos/std_conv.html#.to)在縮小轉換時發生溢出警告。 – rcorre