I've become quite frustrated trying to assign input into 2D Arrays. What's the best way to do it?
I have a 2D array of char type that is initially empty. I want to print out the array once the user has entered 5 rows of input.
I've tried using fgets to assign each character to each position:
I think when the user enters 'abcd' for example, fgets assigns the whole input to [0,0] (during the first loop) instead of each character to [1, 0], [2,0], ..., [5,0] ???Code:#define ROWS 5 #define COLMNS 5 array[5][5]; while(y < COLMNS) { fgets(board[i], ROWS, stdin); i++; y++ ; }
I also tried making a temporary 1D array like so:
The logic behind the above was to assign each row individually in the for loop and when it reached 5 it would switch to the next row.Code:#define ROWS 5 #define COLMNS 5 int y = 0; int i = 0; array[5][5]; line[5]; while(y < COLMNS) { for(i = 0; i < 5; i++) { line[i] = getchar(); line[i] = array[i][y] } i = 0; y = y + 1; }
I also tried a method similar to above but using strcpy to copy the 1D string into the first row of the 2D array but I wasn't sure how to do it correctly.
I really would appreciate help, sorry if some of these questions seem stupid, I am a bit of a n00b. Kind regards.