简体   繁体   中英

C Reading numbers from file into array

hey so im trying to read numbers from text file and put them into an array but ive been getting weird numbers when i try to print them. text file looks like:

45
77
8
...

i guess theres something wrong with the loop im using but i cant seem to find out what. thanks for your help!

code:

#define MAX_ARRAY_SIZE 20

int main(int argc, char * argv[])
{
    FILE *myFile;
    int myArray[MAX_ARRAY_SIZE];
    //char filename[32];
    //printf("enter filename\n");
    //scanf("%s", filename);

    myFile = fopen("asdf.txt", "r");
    if (!myFile) {
        printf("cant open file\n");
        return 1;
    }
    int status;
    int i = 0;
    while ((status = fscanf(myFile, "%2d", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
        ++i;
    }
    fclose(myFile);


    int a;
    for (a = 0; i < MAX_ARRAY_SIZE; ++i) {
        printf("%d ", myArray[i]);
    }
    printf("\n");
return 0;
}

Try this

while ((status = fscanf(myFile, "%d\n", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
    ++i;
}

The problem is in your print loop:

for (a = 0; i < MAX_ARRAY_SIZE; ++i)

There is no guarantee you are reading MAX_ARRAY_SIZE values. Also, if you ar using 'a' as your loop iterator, then you need to use 'a' . Your loop should be:

for (a = 0; a < i; ++a)
    printf("%d ", myArray[a]);

You also do not need a field-width in your format-specifier , fscanf(myFile, " %d", &myArray[i])) will do.

True... I have not seen print loop code.. Sorry. Problem is in print loop not fscan, please ignore my answer

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