简体   繁体   English

读取txt文件中的数字列表并以C格式存储到数组中

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

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 would do something like this: 例如在java中你会做这样的事情:

FileReader file = new FileReader("Integers.txt");
int[] integers = new int [100];
int i=0;
while(input.hasNext())
{
   integers[i] = input.nextInt();
   i++;
}
input.close();

How would this be done in C? 如何在C中完成?

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. 如果你阅读每个函数的手册页(fopen(),scanf(),fclose())以及如何在C中分配数组,你会好得多。你还应该为此添加错误检查。 For example, what happens if Integers.txt does not exist or you don't have permissions to read from it? 例如,如果Integers.txt不存在或您没有从中读取的权限会发生什么? What about if the text file contains more than 100 numbers? 如果文本文件包含超过100个数字呢?

    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);
#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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