How do I read in a .txt file onto an array of integers?

Viewed 44

I have been able to read in a txt file and place each individual int onto an array and this is the closest I've come to succeeding.

int main(){
    int key[100];
    int ch;

    gp = fopen("C:\\file.txt","r");
 
    if (gp == NULL)
    {
        printf("Not printing");
        exit(0);
    }
 
    ch= fgetc(gp);
    while (ch != EOF) {
 
        if(isdigit(ch)) {
            key[i] = ch;
            i++;
        }
        ch = fgetc(gp);
    }
}

With this code I was able to read in each individual number from the file as a character, and successfully print the array. The problem is, I need to be able to access the value of the arrays, and it was storing in the ascii values of the chars.

To fix this, I attempted just subtracting 48 from the chars before assigning the value of ch onto the array, to try to compensate. Like so:

while (ch != EOF) {

    if(isdigit(ch)) {
        key[i] = ch-48;
        i++;
    }
    ch = fgetc(gp);
}

Or letting that loop run and trying in another one.

while (ch != EOF) {

    if(isdigit(ch)) {
        key[i] = ch;
        i++;
    }
    ch = fgetc(gp);
}
for(i=0;i<strlen(key);i++){
    key[i] = key[i]-48;
}

Needless to say, those attempts also didn't work.

My last attempt was trying fscanf(gp, "%d", key);, though this only seemed to work for my first integer. running fscanf through a loop doesn't seem to work either.

for (i=0; i <strlen(key); i++){
    fscanf(gp, "%d", key);
}

So the .txt file that I'm scanning in, looks like this:

4
1 2 3 4
5 6 7 8
9 8 8 7 
9 0 8 4
0 Answers
Related