gpt4 book ai didi

c - 使用函数读取文本文件并记录数组中的值

转载 作者:行者123 更新时间:2023-11-30 16:23:56 26 4
gpt4 key购买 nike

这是我的第一个问题,我仍处于 C 的学习阶段,刚刚开始写一些东西。

我正在编写一个从文本文件(.txt)读取数据的程序,该文件仅包含数字(例如10763.60),每行一个数字。我先写了几行来计算文件中的行数。然后我正在编写代码来读取内容并将其保存到数组中。以下是代码。

FILE *myFile;
myFile = fopen(filename, "r");

//read file into array
float numberArray[count];
int i;

if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < count; i++){
fscanf(myFile, "%f,", &numberArray[i] );
}

fclose(myFile);

现在我正在尝试将其转换为用户定义函数,以便我可以在代码中的各个位置使用它。为此,我尝试遵循。

int *datavalue(int count)
{

float *numberArray = malloc(sizeof(float)*count);

FILE *myFile;
char filename[MAX_FILE_NAME];
printf("\nEnter file name or full path: ");
scanf("%s", filename);
myFile = fopen(filename, "r");

//read file into array

int i;

if (myFile == NULL)
{
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < count; i++)
{
fscanf(myFile, "%f,", &numberArray[i] );
printf("\nThe value is %0.2f",numberArray[i]);
}

fclose(myFile);
return numberArray;
}

但是我无法完成任务。我该怎么做?

最佳答案

小错误, 1)当您正在处理 float 但为 int 分配内存时 2) 重新调整浮点指针,但您声明 datavalue(int count) 作为返回 int

我已经修改了下面的程序,程序按预期工作,按照下面的程序检查并更正。

#include<stdio.h>
#include<stdlib.h>
#define MAX_FILE_NAME 80

float *datavalue(int count) {

float *numberArray = malloc(sizeof(float)*count);

FILE *myFile;
char filename[MAX_FILE_NAME];
printf("\nEnter file name or full path: ");
scanf("%s", filename);
myFile = fopen(filename, "r");

//read file into array

int i;

if (myFile == NULL) {
printf("Error Reading File\n");
exit (0);
}

for (i = 0; i < count; i++)
{
fscanf(myFile, "%f,", &numberArray[i] );
printf("The value is %0.2f\n",numberArray[i]);
}

fclose(myFile);
return numberArray;

}

//主程序如下

 int main()
{
int i = 0;
float *array=NULL;

array = datavalue(5);
for(i = 0; i< 5; i++) {
printf("%f\n", array[i]);
}

return 0;

}

我看到上面程序的以下输出
值为 12.50
值为 14.50
值为 16.50
值为 18.60
值为 6.70
12.500000
14.500000
16.500000
18.600000
6.700000

我的测试文件包含
12.5
14.5
16.5
18.6
6.7
8.9
12.20

关于c - 使用函数读取文本文件并记录数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53792292/

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