disclaimer: I'm a struggling beginner
My assignment is to read integers from an input txt file into a 2D array. When i used printf's to debug/test my fscanf isn't reading the correct values from the file. i can't figure out why.
my code is as follows:
void makeArray(int scores[][COLS], FILE *ifp){
int i=0, j=0, num, numrows = 7, numcols = 14;
for(i = 0; i < numrows; ++i){
for(j = 0; j < numcols; ++j){
fscanf(ifp, "%d", &num);
num = scores[i][j];
}
}
}
int main(){
int scoreArray[ROWS][COLS];
int i=0, j=0;
FILE *ifp;
ifp = fopen("scores.txt", "r");
makeArray(scoreArray, ifp);
system("pause");
return 0;
}
You were assigning num
(what you read from the file) into the value of the array scores[i][j]
which is doing it backwards. The following code will read an arbitrary number of spaces in between each number, until it reaches the end of the file.
void makeArray(int scores[][COLS], FILE *ifp) {
int i=0, j=0, num, numrows = 7, numcols = 14, ch;
for (i=0; i < numrows; ++i) {
for (j=0; j < numcols; ++j) {
while (((ch = getc(ifp)) != EOF) && (ch == ' ')) // eat all spaces
if (ch == EOF) break; // end of file -> break
ungetc(ch, ifp);
if (fscanf("%d", &num) != 1) break;
scores[i][j] = num; // store the number
}
}
}
This Stack Overflow post covers this problem in greater detail.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.