I am coding a c project, that needs that the user enters a N*N square of integers : that’s to say an input of N lines of N integers. The algo works fine.
Now I want the user to input N lines of N integers each of consecutive integers are separated by a space. Here, I don’t have the right usage of scanf, because I tried to declare integers array but I was not able to deal with the spacing.
I tried something like this, very unnatural and failing :
int i=0;
int j=0;
int N;
scanf("%d",&N);
char c[N][2*N-1];
while(i < N){
scanf("%s",&c[i]);
i++;
}
i=0;
j=0;
while (i<N){
while (j<N){
c[i][j]=c[i][2*j]-48;
j++;
}
j=0;
i++;
}
Can someone help ?
Best,
Newben
If I understood what your original code was supposed to do then this code should actually do it (and print it out again just to prove it worked).
You need to dynamically allocate the array since it’s variable size ( In C99 you could use variable sized arrays on the stack but that’s really a different discussion ).
scanf will automatically ignore white-space between the integers (including spaces and new-lines) so you don’t need to parse that out manually.
C99 alternative without malloc/free for completeness (I’v never liked this C99 feature since there’s no way to check that the was/is enough space on the stack):