noobGirlCoding
noobGirlCoding

Reputation: 21

Issues with storing array lengths and array inputs from a given file, where the first integer is the first array's length

I'm having trouble creating a program that reads a file "data.txt" and takes in the first integer of the file as the length of the arrayA and the first integer of the 2nd line in the file as the length of the second arrayB. I'll be sorting these two arrays afterwards but I just need help trying to get the input from the file and store them in the two arrays.

So the file could look like:

4 5 8 6 4
3 8 5 4

The first character '4' means that the length of arrayA is 4 and contains the next 4 following inputs. The 1st character of the second line, '3' means that the length of arrayB is 3. . .

int main(){
    FILE* fileP;
    int aLngth=0, int bLngth=0;
    int i=0, j=0;

    fileP = fopen("data.txt","r");

    fscanf(fileP, "%i", &aLngth);
    int arrayA[aLngth];

    for(i=0; i<=aLngth; i++){
        if(i==0){continue;}
        fscanf(fileP, "%i", &arrayA[i]);//store length a

        if(i+1>aLngth){
            fscanf(fileP, "%i", &bLngth); //store length b
            for(j=0;j<=blLngth; j++){
                 fscanf(fileP, "%i", &arrayB[j]);
            }
        }
    }

    fclose(fileP);
}

Upvotes: 0

Views: 32

Answers (1)

Barmar
Barmar

Reputation: 781769

You should have the second loop after the first one, not inside it.

There's no reason to skip i==0 in the first loop.

You're missing the declaration of arrayB.

The for loops should use < rather than <= in the repeat conditions, because the last index of an array is length-1.

#include <stdio.h>

int main(){
    FILE* fileP;
    int aLngth=0, int bLngth=0;
    int i=0, j=0;

    fileP = fopen("data.txt","r");

    fscanf(fileP, "%i", &aLngth);
    int arrayA[aLngth];
    for(i=0; i<aLngth; i++){
        fscanf(fileP, "%i", &arrayA[i]);
    }

    fscanf(fileP, "%i", &bLngth);
    int arrayB[bLngth];
    for(j=0;j<bLngth; j++){
        fscanf(fileP, "%i", &arrayB[j]);
    }

    fclose(fileP);
}

Upvotes: 1

Related Questions