c语言 - FILE * 是在正确读取先前的条目后从输入文本文件中将零读取到'double'变量中



手头的任务是从输入文件中读取值"as5input.txt";并对这些值进行一些基本的线性计算,以便稍后将它们写入另一个输出文本文件。使用"fscanf((",它成功地读取了前两行数据,然后在应该读取实际值时只读取零。

我在fscanf上尝试了不同的格式,并尝试直接读取以查看它读取的值。我确保输入文件中没有可能导致问题的"\n"或"字符。我还尝试用相同的格式制作一个新的文本文件,以确保文件中没有任何奇怪的错误。然而,它的读数仍然为零。

我认为这与先读一个int,然后读一个double有关,但为什么会这样是没有道理的。

这是我正在使用的文本文件:

as5input.txt

2.0 5.0
6
1.0 2.0 4.0 8.0 16.0 31.0

这就是与之交互的程序:

as5.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct instance_struct
{
int count;
float m, b;
double * x, * y;
};
typedef struct instance_struct instance;
void instance_print(instance *is, FILE * ofp)
{
int i;
fprintf(ofp, "  y = %f x + %fn", is->m, is->b);
for (i = 0; i < is -> count; i++)
{
fprintf(ofp, "  x: %f   y: %fn", is->x[i], is->y[i]);
}
}
instance * make_instance(int count, float m, float b) {
instance * is = (instance *)malloc(sizeof(instance));
is -> m = m;
is -> b = b;
is -> count = count;
is -> x = (double *)malloc(sizeof(double) * count);
is -> y = (double *)malloc(sizeof(double) * count);
return is;
}
int main(void)
{
int i, count;
float m, b;
FILE *ifp, *ofp;
ifp = fopen("as5input.txt", "r");
ofp = fopen("out.txt", "w");
fscanf(ifp, "%f %f %d", &m, &b, &count);
double temp;
instance * is = make_instance(count, m, b);
for (i = 0; i < count; i++) {
fscanf(ifp, "%f", &temp);
printf("%fn", temp);
is -> x[i] = temp;
is -> y[i] = m * temp + b;
}
instance_print(is, ofp);
fclose(ifp);
fclose(ofp);
return 0;
}

这就是输出文件中的内容:

out.txt

y = 2.000000 x + 5.000000
x: 0.000000   y: 5.000000
x: 0.000000   y: 5.000000
x: 0.000000   y: 5.000000
x: 0.000000   y: 5.000000
x: 0.000000   y: 5.000000
x: 0.000000   y: 5.000000

这是第51行打印出来的内容:

0.000000
0.000000
0.000000
0.000000
0.000000
0.000000

我可能错过了一些非常简单的东西,但奇怪的是,它正确地读取了斜率、截距和计数(m,b,count(。如有任何帮助或建议,我们将不胜感激。

double temp;
instance * is = make_instance(count, m, b);
for (i = 0; i < count; i++) {
fscanf(ifp, "%f", &temp);
...
}

您使用%f作为格式说明符,但传递的是double*,而不是float*。增加编译器的警告,您可能会看到这样的警告(例如,gcc/clang的-Wall(:

<source>:50:27: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
fscanf(ifp, "%f", &temp);
~~   ^~~~~
%lf

解决方案是将temp设为float,或者使用%lf作为格式说明符。

请注意,printf%f说明符用于double,因为floats作为doubles传递给具有可变数量参数的函数。这不适用于指针。

最新更新