Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

i am trying to read a file in c language the file structure is in array and i have to seperate it into array x[] and y[]

My code is to find line number and then print all element in it but it is throwing garbage value and main thing to do is to seperate front one as x and y respectively plese help me seperate x[] = [60,15,62.....] and y[] = [229,221,59,....]

Dataset is

60,229
15,221
62,59
96,120
16,97
41,290
52,206
...

#include <stdio.h>
#include <stdlib.h>

int main(){

    FILE *myFile;
    myFile = fopen("datasetLR1.txt", "r");
    int count=0;
    char c;
    for (c = getc(myFile); c != EOF; c = getc(myFile)) {
        if (c == '
'){
            count = count + 1; 
        }// Increment count if this character is newline 
            
    }
    
    int numberArray[count*2];
    int i;

    if (myFile == NULL){
        printf("Error Reading File
");
        exit (0);
    }

    for (i = 0; i < count*2; i++){
        fscanf(myFile, "%d,", &numberArray[i] );
    }

    for (i = 0; i < count*2; i++){
        printf("Number is: %d

", numberArray[i]);
    }

    fclose(myFile);

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After you count the number of lines in the file with your first for loop, you should use rewind(myFile);. This puts you back to the beginning of the file. Without this, you are reading off the end of the file, which is producing the garbage values. Other than that, your code works fine.

You should also look at doing fscanf("%d,%d ", &x, &y);, which should read off both numbers at once (and the newline) and assign them to x and y respectively. This should simplify your code significantly, however, your code works fine without it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...