简体   繁体   中英

Inputting from a file to an array in C, after eof

I'm trying to put all of the information in a file into an array, after I have already looped through the file to see how many lines the file is. If I putc a line of the file it seems to work, however, if I set the array locations to the file lines as I go back through the file and then print the array, the numbers come out way different from what they should be.

Here's my code.

int main()
{

                            //Opens File

    char fName[20];

   // fName = getchar();

    scanf( "%s", fName);

    FILE *fpIn;

    fpIn = fopen ( fName, "rt");
   // fpIn = fopen( "test1.txt", "rt");

    if ( fpIn == NULL)
    {
        printf( "Unable to open: ");
        exit(99);
    }

                            //Gets Lines

    int lines=0;
    char ch;

    while((ch=fgetc(fpIn))!=EOF)
    {
        if (ch=='\n') { lines++; }

    }

    clearerr(fName *fpIn);
    fclose(fpIn);
    fopen(fName, "rt");

                            //Makes Array

    int *pA;

    pA = (int *)malloc(lines*sizeof(int));

                            //Fills Array

    for (int i=0; i<lines; i++)
    {
        while ((ch=fgetc(fpIn))!='\n')
        {
            pA[i] = ch;
        }
        ch=fgetc(fpIn);
    }

    for (int i=0; i<lines; i++)
    {
        printf("%d\n", pA[i]);
    }



    return 0;
}

Consider this part of the code:

    while ((ch=fgetc(fpIn))!='\n')
    {
        pA[i] = ch;
    }

i doesn't change during this loop, so pA[i] keeps being overwritten with each new character. You'll end up with pA[i] containing the last character on the line.

While switching to the fscanf() statement instead of the getc() as suggested by Vaughn Cato was definitely helpful in getting me towards the right solution. What made the real difference was removing the while statement that checked to make sure I had reached the end of the line before moving on to the next integer.

The code now reads,

for (int i=0; i<lines; i++)
    {
        fscanf(fpIn, "%lf", &pA[i]);
    }

And, so far, appears to work for all the appropriate data input files.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM