I am attempting to write code for reading a matrix reader that will read in a matrix from a redirected file (so FILE functions will not be used in my program), store it in a dynamically created array and then print out to console.
Important note Array is dynamic (meaning that the dimensions are obtained by reading the entire file and calculating the # of rows & columns.
I have tried writing code 2 different ways to do this and both result in wrong output:
Version A:
while(ch != EOF) {
ch = fgetc(stdin);
if(ch == ' ') {
fields++;
}
if(ch == '\n') {
rows++;
}
}
Version B:
do {
c=getchar();
if(c == ' '){
fields++;
}
} while (c != EOF);
Question
- Does
while(ch != EOF)orwhile(c=getchar() != EOF)mean while it does not hit end of a LINE, or end of the FILE?
I have had little luck with Version B shown above. When used on test file:
10 20 30 40
50 60 70 80
90 10 20 30
40 50 60 70
I get output:
50 60 70 80
90 10 20 30
40 50 60 70
70 70 70 70
I think the problem I am having here is that whenever I am reading my file once it hits EOF it breaks out of the loop, and then it is on the 2nd line of the file, hence why the output starts at the 2nd line, and then duplicates the last number X times to fill the rest of the matrix.
Is my goal here achievable with my current methods? Here is all of my code, Thanks.
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows=0;
int fields=1;
int i=0;
int j=0;
int c=0;
char ch = '\0';
/* while(ch != EOF) {
ch = fgetc(stdin);
if(ch == ' ') {
fields++;
}
if(ch == '\n') {
rows++;
}
} */
do {
c=getchar();
if(c == ' '){
fields++;
}
} while (c != 10);
int **array;
array = malloc(fields * sizeof(int *));
if(array == NULL) {
printf("Out of memory\n");
exit(1);
}
for(i = 0; i < fields; i++) {
array[i] = malloc(fields * sizeof(int));
if(array[i] == NULL) {
printf("Out of memory\n");
exit(1);
}
}
for(i = 0; i < fields; i++) {
for(j = 0; j < 4; j++) {
int k;
scanf("%d", &k);
array[i][j] = k;
printf("%d ", k);
}
printf("\n");
}
}
while(c=getchar() != EOF)should bewhile((c=getchar()) != EOF)add parentheses. first assign then compare, you are assigning result of comparison to C then comparison returns0your loop breakswhile (c != EOF)towhile(c != 10)However I do believe that these are technically doing the same thing. Right? Also, adding a parenthesis resulting in my output being all 0's, and it output a 4x13 matrix so yeah, any idea what is going on here now?while((c=getchar()) != EOF)and then fields++ ifc == ' 'and rows++ ifc == '\n'results in a huge matrix of only 0's.