gpt4 book ai didi

c - 从 C 数组中的 txt 文件第二行读取数字

转载 作者:行者123 更新时间:2023-11-30 14:45:02 26 4
gpt4 key购买 nike

我确实有一个如下所示的 txt 文件

10
41 220 166 29 151 47 170 60 234 49

如何将第二行中的数字读取到 C 中的数组中?

int nr_of_values = 0;
int* myArray = 0;
FILE *file;
file = fopen("hist.txt", "r+");
if (file == NULL)
{
printf("ERROR Opening File!");
exit(1);
}
else {
fscanf(file, "%d", &nr_of_values);
myArray = new int[nr_of_values];

// push values from second row to this array
}

最佳答案

How can I read only the numbers from the second row into an array in C?

通过读取并丢弃第一行来忽略它。

你可以使用类似的东西:

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

int main(void)
{
char const *filename = "test.txt";
FILE *input_file = fopen(filename, "r");

if (!input_file) {
fprintf(stderr, "Couldn't open \"%s\" for reading :(\n\n", filename);
return EXIT_FAILURE;
}

int ch; // ignore first line:
while ((ch = fgetc(input_file)) != EOF && ch != '\n');

int value;
int *numbers = NULL;
size_t num_numbers = 0;
while (fscanf(input_file, "%d", &value) == 1) {
int *new_numbers = realloc(numbers, (num_numbers + 1) * sizeof(*new_numbers));
if (!new_numbers) {
fputs("Out of memory :(\n\n", stderr);
free(numbers);
return EXIT_FAILURE;
}
numbers = new_numbers;
numbers[num_numbers++] = value;
}

fclose(input_file);

for (size_t i = 0; i < num_numbers; ++i)
printf("%d ", numbers[i]);
putchar('\n');

free(numbers);
}

关于c - 从 C 数组中的 txt 文件第二行读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53302541/

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