gpt4 book ai didi

c - 将数据文件作为整数数组发送和接收到 C 中的函数

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

我正在尝试将数组元素传递给从文件访问的函数。但是我不知道我的声明有什么问题,

这是代码,请帮帮我。

/*This program takes some random data from a file and 
prepares a histogram for it.
*/

int getdata(int data[],FILE fptr1);

#include<stdio.h>

main()
{
int i,hist[15]={0},elements[15],data[80];
FILE * fptr1;

printf("welcome buddy\n");
getdata(data,fptr1);

for(i=1;i<80;i++)
fprintf(stdout,"%2d",data[i]);

}

int getdata(int data[],FILE fptr1)
{
fptr1=fopen("sampledata.txt","r");

if(fptr1==NULL)

printf("the file is not opened properly\n");

//for(i=0;i<=79;i++)

//scanf(fptr1,"%d",&data[i]);

while((scanf(fptr1,"%d",&data)!=EOF))
;

fclose(fptr1);

return data;
}

最佳答案

改变

int getdata(int data[],FILE fptr1);

void getdata(int (*data)[80],FILE* f(*data)[80]ptr1)
/* Case 1
* You need a pointer to 80 member integer array
* fptr1 is a pointer, a pointer should be passed as a pointer
*/

 void getdata(int data[80],FILE* f(*data)[80]ptr1)
/* Case 2
* fptr1 is a pointer, a pointer should be passed as a pointer
*/

改变

(scanf(fptr1,"%d",&data)!=EOF)

(fscanf(fptr1,"%d",data[i])==1) //case1
// data is a pointer,so no ampersand preceeding it
// fscanf returns the number of values filled

(fscanf(fptr1,"%d",&data[i])==1) //case2

// fscanf returns the number of values filled

然后删除

return data;

建议

维护一个读取值的数量是很好的,你可以放

int count=0;

在函数的开头然后做

while((fscanf(fptr1,"%d",&data)==1))
count++;

并替换

return data;

return count; // here function return type should be int.

在main函数中捕获count的值并打印直到count为止的元素。

关于c - 将数据文件作为整数数组发送和接收到 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37290759/

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