Read list of numbers in txt file and store to array in C

后端 未结 2 1799
夕颜
夕颜 2020-12-15 14:08

I have a list of integers, one number per line and would like to store each of these numbers in an integer array to use later in the program.

For example in java you

相关标签:
2条回答
  • 2020-12-15 14:58
    #include <stdio.h>
    
    int main (int argc, char *argv[]) {
      FILE *fp;
      int integers[100];
      int value;
      int i = -1; /* EDIT have i start at -1 :) */
    
      if ((fp = fopen ("Integers.txt", "r")) == NULL)
        return 1;
    
      while (!feof (fp) && fscanf (fp, "%d", &value) && i++ < 100 )
        integers[i] = value;
    
      fclose (fp);
    
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-15 15:04

    Give this a go. You'll be much better off if you read the man pages for each of these functions (fopen(), scanf(), fclose()) and how to allocate arrays in C. You should also add error checking to this. For example, what happens if Integers.txt does not exist or you don't have permissions to read from it? What about if the text file contains more than 100 numbers?

        FILE *file = fopen("Integers.txt", "r");
        int integers[100];
    
        int i=0;
        int num;
        while(fscanf(file, "%d", &num) > 0) {
            integers[i] = num;
            i++;
        }
        fclose(file);
    
    0 讨论(0)
提交回复
热议问题