gpt4 book ai didi

c - fscanf 不从文件读取

转载 作者:行者123 更新时间:2023-11-30 14:51:32 25 4
gpt4 key购买 nike

我试图从我的txt文件中读取一些输入,但我不知道为什么它不读取......我做错了什么?

文件内容: 3 1.0 0.05 0.2 0.5

读取函数:

float * le_dados_ficheiro(char *nomeFich,int *nMoedas, float *valor)
{
FILE *f;
float *p,*q;
int i;

f = fopen(nomeFich,"r");
if(!f)
{
printf("Erro ao abrir ficheiro %s\n",nomeFich);
exit(1);
}

fscanf(f," %d %f",nMoedas,valor);//**It is empty after this**

p = malloc(sizeof(float)*(*nMoedas));
if(!p)
{
printf("Erro ao reservar memoria ... \n");
exit(1);
}

q = p;
for(i = 0; i < *nMoedas; i++)
fscanf(f," %f",q++);

fclose(f);

printf("%f - %f - %f",q[0],q[1],q[2]);//**Still empty**
return q;
}

最佳答案

您只是在这里打印了错误的数据:

printf("%f -  %f  - %f", q[0], q[1], q[2]);

q 指向数组末尾之后。您需要打印p:

printf("%f -  %f  - %f", p[0], p[1], p[2]);

否则,如果文件的确切内容如下,您的程序就可以正常工作:

3 1.0
0.05 0.2 0.5

通过错误检查纠正代码:

float *le_dados_ficheiro(char *nomeFich, int *nMoedas, float *valor)
{
FILE *f;
float *p, *q;
int i;

f = fopen(nomeFich, "r");
if (!f)
{
printf("Erro ao abrir ficheiro %s\n", nomeFich);
exit(1);
}

if (fscanf(f, " %d %f", nMoedas, valor) != 2)
{
printf("Wrong file format ... \n");
exit(1);
}

p = malloc(sizeof(float)*(*nMoedas));
if (!p)
{
printf("Erro ao reservar memoria ... \n");
exit(1);
}

q = p;
for (i = 0; i < *nMoedas; i++)
{
if (fscanf(f, " %f", q++) != 1)
{
printf("Wrong file format ... \n");
exit(1);
}
}

fclose(f);

printf("%f - %f - %f", p[0], p[1], p[2]);
return q;
}

关于c - fscanf 不从文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48222279/

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