c++ - How to add user input into a 2D array -
i'm trying get user input, stored in array (eightbit[]), , add 2d array (board). user supposed enter 8 numbers, example: byte 1: 1 byte 2: 2 etc... , output supposed like:
1 2 3 4 5 6 7 8
however output get:
8 8 8 8 8 8 8 8
any idea why repeating last numbered entered? part of code below, appreciated.
cout << "enter pattern of 8 bits:" << endl; for(i = 0; < 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; }
that's because of outer loop i
overwriting every element in 2d array.
a solution drop outer loop entirely, so:
int = 0; for(int j=0; j<2; j++) { for(int k=0; k<4; k++) { board[j][k] = eightbit[i++]; } }
also have bracket mismatch in code snippet.
Comments
Post a Comment