它看起来很常见而且很明显,但我过去已经在 C 中阅读过 txt 文件,但在这里我真的被卡住了。
我有一个这种格式的txt文件
0.00000587898458 0.0014451541000 0.000000000001245
0.00012454712235 0.1245465756945 0.012454712115140
... 有 640 列和 480 行。
我想将我的 txt 文件中的每个数字尽可能精确地放在一个 float 中,并放在一个 for 循环中。
FILE* myfile=NULL;
double myvariable=0.0;
myfile=fopen("myfile.txt","r");
for(i =0, k=0 ; i< height; i++)
for (j=0 ; j< width ; j++){
fscanf(myfile,"%0.20f",&myvariable);
printf("%0.20f",myvariable);
k++;
}
}
fclose(myfile);
非常感谢您的帮助
最佳答案
您的程序中有几个错误 - 大括号不匹配、 undefined variable 等。然而,最重要的也是最有可能导致您的问题的错误是您没有将指针传递给 myvariable
在您的 fscanf()
调用中。您需要在那里使用 &myvariable
,以便 fscanf()
可以适本地填充它。您可能不需要如此复杂的格式字符串 - "%lf"
应该可以很好地读取 double
。事实上,gcc
会用您的格式字符串警告我:
example.c:16: warning: zero width in scanf format example.c:16: warning: unknown conversion type character ‘.’ in format
然后我的输出就变成了 0。试试 "%lf"
。这是一个完整的示例输入示例:
#include <stdio.h>
#define HEIGHT 2
#define WIDTH 3
int main(void)
{
FILE *myfile;
double myvariable;
int i;
int j;
myfile=fopen("myfile.txt", "r");
for(i = 0; i < HEIGHT; i++)
{
for (j = 0 ; j < WIDTH; j++)
{
fscanf(myfile,"%lf",&myvariable);
printf("%.15f ",myvariable);
}
printf("\n");
}
fclose(myfile);
}
运行示例:
$ ./example
0.000005878984580 0.001445154100000 0.000000000001245
0.000124547122350 0.124546575694500 0.012454712115140
关于c - 在 C 中读取包含 float 的 .txt 文本文件,以空格分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7151922/