我开始自学C语言了。我自己也一直在努力学习其他语言(例如 Java、HTML、CSS)。无论如何,我有一个关于将数字文本文件插入 int 数组的基本问题。
这就是我开始的方式(如果我做错了什么,请告诉我)。
我使用 Linux 命令提示符创建了一个文本文件:cat > input.txt
我在 input.txt 中输入了我选择的随机数:14 21 78 14
我想以某种方式将 input.txt 中的数字加载到我在 arrayTest.c 文件中创建的数组中。
这是我制作的数组:
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
我一直在看教程,但似乎无法理解。
最佳答案
查看文件操作的文档; fopen、fread 和 fclose。 这些使您的代码可以访问文件的内容。
一旦您读取了数据,或者作为读取的一部分,您就可以获得单独的数字。
您可以通过将任务分解为更小的部分来学习,例如,假设您已经将文件读入字符串中,然后只处理该部分以从中获取数字。
关于c - C 读取文本文件并将数字插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35263128/