2013-03-24 116 views
-2

我試圖獲取用戶輸入,它存儲在一個數組(eightBit [])中,然後將其添加到二維數組(板)。用戶應該輸入8個數字,一個例子: 字節1:1個 字節2:2 等等 和輸出應該是這樣的:如何將用戶輸入添加到二維數組中

1 2 3 4 
5 6 7 8 

然而,這是輸出我得到:

8 8 8 8 
8 8 8 8 

任何想法爲什麼它只重複最後一個數字進入?我的部分代碼如下,任何幫助將不勝感激。

cout << "Enter a pattern of eight bits:" << endl; 
      for(i = 0; i < 8; i++){ 
       cout << "Byte " << i+1 << ": "; 
       cin >> eightBit[i]; 
      } 

int board[2][4]; 

      for(i = 0; i<8; i++){ 
       for(int j=0; j<2; j++){ 
       for(int k=0; k<4; k++) { 
        board[j][k] = eightBit[i]; 

       } 
      } 

      for(int j=0; j<2; j++) 
      { 
       for(int k=0; k<4; k++) 
       { 
        cout << board[j][k] << " "; 
       } 
    cout << endl; 
} 
+0

您從'eightBit'複製到'board'的'for'循環周圍的'{'和'}對不會相加 - 它們可能對您的問題至關重要。你可以嘗試發佈可編譯代碼嗎? – 2013-03-24 21:49:34

回答

0

這很自然。在第二個時候,當我獲得最後8個,那麼董事會充滿了當前我(我= 8)。 試試這個,下一次更加小心你的代碼:)。

#include <iostream> 

using namespace std; 
int eightBit[2][4]; 

int main() 
{ 
    cout << "Enter a pattern of eight bits:" << endl; 

     for(int i = 0; i <2; i++){ 
      for (int j=0 ; j<4 ; ++j) { 
       cout << "Byte " << (j+1)+4*i << ": "; //4 = # of columns,i=row,j=column. 
       cin >> eightBit[i][j]; 
      } 
     } 


    int board[2][4]; 


    for(int i = 0; i <2; i++){ 
     for (int j=0 ; j<4 ; ++j) { 
      board[i][j] = eightBit[i][j]; 

     } 
    } 
    for(int i = 0; i <2; i++){ 
     for (int j=0 ; j<4 ; ++j) { 

      cout << board[i][j] << " "; 
     } 
     cout << endl; 
    } 

} 
+0

linear index = row * numCols + col – Recker 2013-03-24 22:14:55

+0

是的,這樣更清晰。 – trmag 2013-03-24 22:18:19

2

那是因爲你與i它基本上覆蓋在你的二維數組的每一個元素外循環。

一個解決方案是完全丟棄外環,就像這樣:

int i = 0; 
    for(int j=0; j<2; j++) { 
     for(int k=0; k<4; k++) { 
      board[j][k] = eightBit[i++]; 
     } 
    } 

你也有你的代碼片段支架不匹配

相關問題