gpt4 book ai didi

c - ANSI C 从文件中分离数据

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:55 25 4
gpt4 key购买 nike

我有一个包含类似数据的文件

zz:yy:xx.xxx [-]pp.pp

减号是可选的。我需要分离数据。我需要那个 [-]pp.pp 到 float 类型的下一个 Action 。我怎样才能用那部分数据制作一个 float 组?

我在这里打开文件并打印所有数据。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 2000
FILE *file;
int main()
{
file = fopen("data.txt" , "r");
int i,znak=0;
char string[N];
while ((znak = getc(file)) != EOF)
{
string[i]=znak;
printf("%c",string[i]);
i++;

}
return 0;
}

最佳答案

这样试试

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

#define FORMAT "%*[^:]:%*[^:]:%*[^: ] %f"

int main(void)
{
FILE *file;
float value;
int size;
float *array;
// Open the file
file = fopen("data.txt", "r");
// This is really important
if (file == NULL) {
fprintf(stderr, "Can't open the file\n");
return -1;
}
size = 0;
// Count the number of entries in the file
while (fscanf(file, FORMAT, &value) == 1) {
size += 1;
}
// Reset the file position to the beginning
rewind(file);
// Allocate space for the array
array = malloc(size * sizeof(*array));
// And, ALWAYS check for errors
if (array == NULL) {
fprintf(stderr, "Out of memory\n");
fclose(file);
return -1;
}
// Extract the data from the file now
for (int i = 0 ; i < size ; ++i) {
fscanf(file, FORMAT, &array[i]);
}
// The file, is no longer needed so close it
fclose(file);
// Do something with the array
handle_array(size, array);
// Free allocated memory
free(array);
return 0;
}

关于c - ANSI C 从文件中分离数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40202602/

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