读取txt文件中的数字列表并存储到C中的数组 [英] Read list of numbers in txt file and store to array in C

查看:25
本文介绍了读取txt文件中的数字列表并存储到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.

例如在java中你会做这样的事情:

For example in java you would do something like this:

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 中完成?

How would this be done in C?

推荐答案

试试这个.如果您阅读这些函数(fopen()、scanf()、fclose())中的每一个的手册页以及如何在 C 中分配数组,您的情况会好得多.您还应该为此添加错误检查.例如,如果 Integers.txt 不存在或者您没有读取它的权限会发生什么?如果文本文件包含超过 100 个数字怎么办?

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

这篇关于读取txt文件中的数字列表并存储到C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆