加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:42:31 所属栏目:百科 来源:网络整理
导读:我有一个整数列表,每行一个数字,并希望将这些数字存储在一个整数数组中,以便稍后在程序中使用. 例如在java中你会做这样的事情: FileReader file = new FileReader("Integers.txt");int[] integers = new int [100];int i=0;while(input.hasNext()){ integer
我有一个整数列表,每行一个数字,并希望将这些数字存储在一个整数数组中,以便稍后在程序中使用.

例如在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();

如何在C中完成?

解决方法

放手一搏.如果你阅读每个函数的手册页(fopen(),scanf(),fclose())以及如何在C中分配数组,你会好得多.你还应该为此添加错误检查.例如,如果Integers.txt不存在或您没有从中读取的权限会发生什么?如果文本文件包含超过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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读