There are a lot of questions like this in stack, but I could not find one on the specific issue thus I decided to post..
I get my input from a text file which is always structured like this:
X Y
A1 A2 AY
A4 A5 ..
AX .. ..
Dimensions of a 2d array on the first line and a 2d array composed of characters with X rows and Y columns.
Something goes wrong while transitioning from the first row of the text file to the rest.
My code for the input is the following:
#include<stdio.h>
#include<stdlib.h>
int n,m;
int main(int argc,char **argv){
if(argc!=2){
perror("Error: ");
return EXIT_FAILURE;
}
FILE* txtfile=fopen(argv[1],"r");
if(txtfile<0){
perror("Error: ");
return EXIT_FAILURE;
}
char lab[n][m];
fscanf(txtfile,"%d %d",&n,&m);
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
fscanf(txtfile," %c",&lab[i][j]);
}
}
An example input is the following:
3 3
ULD
LUD
LRL
Which produces the result:
lab[0][0] = L
lab[0][1] = R
lab[0][2] = L
lab[1][0] = L
lab[1][1] = R
lab[1][2] = L
lab[2][0] = L
lab[2][1] = R
lab[2][2] = L
Which is obviously wrong... If I provide n,m through user input through the terminal or give them a value inside my program (n=3 and m=3 in this case), and remove them from the text file:
ULD
LUD
LRL
I then get the correct 2d array:
lab[0][0] = U
lab[0][1] = L
lab[0][2] = D
lab[1][0] = L
lab[1][1] = U
lab[1][2] = D
lab[2][0] = L
lab[2][1] = R
lab[2][2] = L
I have tried using fseek to move the pointer in the file to the second line after the first is read, but without results.
Any help/explanation is appreciated, I'm still new to C.