它看起来很常见而且显而易见但我已经在过去读过C中的txt文件,而且我真的被卡住了.
我有这种格式的txt文件
0.00000587898458 0.0014451541000 0.000000000001245
0.00012454712235 0.1245465756945 0.012454712115140
Run Code Online (Sandbox Code Playgroud)
...有640列和480行.
我想将我的txt文件的每个数字放在一个浮点数中,尽可能保持最大精度,并在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);
Run Code Online (Sandbox Code Playgroud)
非常感谢您的帮助
你的程序中有几个错误 - 不匹配的大括号,未定义的变量等.然而,最重要的是,最可能导致你的问题的是,你没有myvariable
在你的fscanf()
通话中传递指针.你会想在&myvariable
那里使用,所以fscanf()
可以适当填写它.您可能也不需要格式字符串这么复杂 - "%lf"
应该可以正常工作来阅读double
.事实上,gcc
用你的格式字符串警告我:
Run Code Online (Sandbox Code Playgroud)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);
}
Run Code Online (Sandbox Code Playgroud)
示例运行:
$ ./example
0.000005878984580 0.001445154100000 0.000000000001245
0.000124547122350 0.124546575694500 0.012454712115140
Run Code Online (Sandbox Code Playgroud)