读取文本文件并在C中将数字插入数组

时间:2016-02-08 05:50:50

标签: c arrays

我自己开始学习C语言。我一直在努力学习其他语言(例如Java,HTML,CSS)。无论如何,我有一个关于将数字文本文件插入int数组的基本问题。

这就是我开始的方式(如果我做错了,请告诉我。)

  1. 我使用Linux命令提示符创建了一个文本文件: cat> input.txt中

  2. 我输入了我选择的随机数字到input.txt: 14 21 78 14

  3. 我想以某种方式将input.txt中的数字加载到我在arrayTest.c文件中创建的数组中。

  4. 这是我制作的数组:

    main() {
    int num[100]; // My array that I want to insert numbers from input.txt into
    }
    
    void readNumbers() { // Function that reads the numbers
    /* Not really sure how to start this -- help would be nice */
    }
    
    void displayNumbers() { // Function that displays the numbers in the output
    printf("Your numbers are:\n", num[1], num[2], num[3], num[4]); // Just an example
    

    然后输出显示如下:

    Your numbers are: 14 21 78 14
    

    我一直在看教程,我似乎无法得到它。

2 个答案:

答案 0 :(得分:1)

查看文件操作的文档; fopen,fread和fclose。 这些允许您的代码访问文件的内容。

一旦您阅读了数据或作为阅读的一部分,您就可以获得个人数字。

您可以通过将任务分解为更小的部分来学习,例如,假装您已经将文件读入字符串中,并且只是在部件上工作以获取数字。

答案 1 :(得分:0)

你可以像这样阅读C

{{1}}

聚苯乙烯。 @barak manos对于您声明的{{1}}数组的范围是正确的。

相关问题