简体   繁体   中英

In C is their anyway way to read the contents of a file, line-by-line, and store each integer value (preline) into a array separately?

My C Code is as so:

#include <stdio.h>

int main( int argc, char ** argv){

    FILE *myFile;
    myFile = fopen("numbers.txt", "r");

    //read file into array
    int numberArray[16];
    for (int i = 0; i < 16; i++){
        fscanf(myFile, "%1d", &numberArray[i]);
    }

    for (int i = 0; i < 16; i++){
      printf("Number is: %d\n", numberArray[i]);
    }
}

My numbers.txt file contains the follow values:

5
6
70
80
50
43

But for some reason my output

Number is: 5
Number is: 6
Number is: 7
Number is: 0
Number is: 8
Number is: 0
Number is: 5
Number is: 0
Number is: 4
Number is: 3
Number is: 0
Number is: 0
Number is: 4195904
Number is: 0
Number is: 4195520
Number is: 0

However I'm expecting it to print out numberArray to print out the identical contents of the text file. I'm not exactly sure why it's doing this, does anyone happen to know the reason? I'm aware that I'm making an array bigger than the amount of values that I can store, but I'm still confused as to why it can't store 70, 80, etc into one index?

It is because you are reading only 1 digit at a time.

Hence change the below.

fscanf(myFile, "%1d", &numberArray[i]);

to

fscanf(myFile, "%d", &numberArray[i]);

And your array should be of size number of integers in the file.

int numberArray[6];

for (int i = 0; i < 6; i++)

or

while (fscanf(myFile, "%d", &numberArray[i++]) == 1);

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

int main(void) {
    FILE *myFile = fopen("numbers.txt", "r"); // just init your variable directly
    if (!myFile) { // Always check if there is no error
        return EXIT_FAILURE; // handle it as you like
    }

    #define SIZE 16 // Avoid magic number
    int numberArray[SIZE];
    size_t n = 0; // n will represent the size of valid values inside the array
    // Always check if scanf family has parsed your input also "%1d" ask to only parse
    // one digit, so use %d if you want parse an integer
    while (n < SIZE && fscanf(myFile, "%d", numberArray + n) == 1) {
        n++;
    }

    for (size_t i = 0; i < n; i++) {
      printf("Number is: %d\n", numberArray[i]);
    }
}

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