2012-10-20 43 views
0

對於我的任務之一,我必須使用getline來查看二維數組。迷宮設計是當場製作的。使用getline輸入到二維數組中

16 10 
################ 
#  # # # 
# # #### ## ## 
# #  ####### 
# ###### #E # 
#S# # # ### ### 
# # ## #  # # 
# # ## ####### # 
#    # 
################ 

這是將要測試我們的回溯算法的示例輸入之一。

16 10是我們迷宮的列和行。

我在想如何正確解析getline,這樣我的2D數組就會填充使用給出的迷宮。

在一個側面說明,我犯了一個實踐之一,我沒有對CIN,而是已經有我的數組,我不知道我怎麼會告訴它在S.

遺憾地開始,如果那裏有一個問題在這個,但我沒有真正看到一個在這個格式中,你不知道你的數組大小,進入一個二維數組。

+0

像這樣:http://stackoverflow.com/questions/12992600/convert-string-to-char-2d-array?也許你們有相同的功課。 –

+0

我回答了這個問題。有關直接鏈接,請參閱:http://stackoverflow.com/a/12992851/1732980。 –

+0

不一樣,但我相信這會奏效。其基本相同,只是我必須設置我的列和行。 TY –

回答

1

getline將一次只讀取一行,因此您可能想要做的就是使用for循環依次讀取每行並將其存儲爲2d數組的一行。

0

試試這個:

size_t num_rows; 
size_t num_cols; 

cin >> num_rows >> num_cols; 

char* maze = new char[num_rows * num_cols]; 

for (size_t row = 0; row < num_rows; row++) 
{ 
    string line; 

    getline(cin, line); 

    if (line.size() != num_cols) 
    { 
     cerr << "Error! Size is " << line.size() << " rather than " << num_cols << endl; 
     exit(1); 
    } 

    for (size_t col = 0; col < num_cols; col++) 
    { 
     maze[(row * num_cols) + col] = line[col]; 
    } 
} 

cout << "Maze is: " << endl; 

for(int row = 0; row < num_rows; row++) 
{ 
    for(int col = 0; col < num_cols; col++) 
    { 
     cout << maze[(row * num_cols) + col]; 
    } 

    cout << endl; 
} 

delete [] maze; 

要找出其中的開端是:

size_t start_row, start_col; 

for(int row = 0; row < num_rows; row++) 
{ 
    bool found = false; 

    for(int col = 0; col < num_cols; col++) 
    { 
     if (maze[(row * num_cols) + col] == 'S') 
     { 
      start_row = row; 
      start_col = col; 
      found = true; 
      break; 
     } 
    } 

    if (found) 
    { 
     break; 
    } 
} 

可以爲終點做類似的事情。

如果您想將起始點置於隨機空白處,可以使用srandrand

首先,在你的程序開始播種的僞隨機數生成器:

srand(time(0)); 

然後,確定一個隨機起點:

size_t start_row, start_col; 
bool found = false; 

while (!found) 
{ 
    start_row = rand() % num_rows; 
    start_col = rand() % num_cols; 

    if (isspace(maze[(start_row * num_cols) + start_col])) 
    { 
     maze[(start_row * num_cols) + start_col] = 'S'; 
     found = true; 
    } 
} 

你可以把結束點隨機空以類似的方式發現。

人們將sy srandrand不擅長隨機數字的產生。這是真的,但它應該足以滿足您的需求。

+0

我不使用刪除嗎?這僅僅是爲了這個例子? –

+0

當您完全使用數組時,可以使用'delete'。 –

+0

'delete'操作符與'new'操作符相反。每個'new'需要1個'delete'。但是在你完成記憶之前你不會調用它。 –