gpt4 book ai didi

c - 如何从文件中获取所有数字并将它们输入到数组中?

转载 作者:行者123 更新时间:2023-11-30 19:37:09 24 4
gpt4 key购买 nike

所以我可以有一个输入文件,文件中的每个数字之间可以有空格或换行。例如:

input.txt
2 3 4
4 3 2 3
2 3 1
5 4 3 2
2 5 4 2

我如何解析文件并获取所有元素并将它们放入数组中。目前我有以下代码:

#include<stdio.h>
#define FILE_READ "input.txt"

int main()

{
FILE * filp;
int count = 1;
char c;
filp = fopen(FILE_READ, "r");
if(filp == NULL)
printf("file not found\n");
while((c = fgetc(filp)) != EOF) {
if(c == ' ')
count++;
}
printf("numbers = %d\n", count);
return 0;
}
int myarray[count-1];

那么此时我到底该如何将数字插入数组呢?我获取了文件中的数字数量并创建了一个数字大小的数组。现在我到底该如何将数字放入数组中?

最佳答案

这是一件非常简单的事情,只需使用 fscanf() 来计算有多少个值,然后使用 malloc() 为它们分配空间。然后,再次使用 fscanf() 将值读入数组。

这可能看起来工作量很大,但为每个值分配空间的工作量更大。一种值得付出努力的优化是分配一个估计大小的数组,然后在空间不足时使用 realloc() 将数组增长为初始估计的倍数。这样,您可以减少分配次数,同时只需循环访问值(从文件中读取一次也很昂贵)。

这是我认为最简单的方法

#include <stdlib.h>
#include <stdio.h>

int
main(void)
{
FILE *file;
int count;
int value;
file = fopen("input.txt", "r");
if (file == NULL)
return -1; // Error opening the file
count = 0;
while (fscanf(file, "%d", &value) == 1)
count += 1;
if (count > 0) {
int *array;

rewind(file);
array = malloc(count * sizeof(*array));
if (array == NULL) {
fclose(file);
return -1;
}
count = 0;
while (fscanf(file, "%d", &array[count]) == 1) {
fprintf(stdout, "%d\n", array[count]);
count += 1;
}
// Use the array now and then
free(array);
}
fclose(file);
return 0;
}

关于c - 如何从文件中获取所有数字并将它们输入到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40229689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com