[英]Reading multiple lines of doubles with fscanf
I have an input file which contains six doubles on every line, which I would like to be read by fscanf. 我有一个输入文件,每行包含六个双打,我想由fscanf读取。 However, after reading the numbers from the input file, all stored values are zero. 但是,从输入文件中读取数字后,所有存储的值均为零。 For example: 例如:
Input: 输入:
8.260358155 0.217414463 0.079918794 -0.068255156 -0.124913458 0.821136998
0.095921056 0.878265878 1.099486349 0.766342809 1.918243674 0.476907831
1.050441605 8.451442631 0.945819695 -0.440024089 -1.149013541 0.374284191
Code: 码:
double r[NMAX][3];
double rv[NMAX][3];
int nAtom = 3;
int n;
FILE *loadFile = fopen(LoadName,"r");
if (loadFile == NULL){
printf("ERROR: can't open loadFile\n");
exit(1);
}
fscanf(loadFile,"%d",&nAtom);
for (n=0; n<nAtom; ++n){
fscanf(loadFile, "%f %f %f %f %f %f",
&r[n][0],&r[n][1],&r[n][2],&rv[n][0],&rv[n][1],&rv[n][2]);
}
fclose(loadFile);
for (n=0; n<nAtom; ++n){
printf("%12.9f %12.9f %12.9f %12.9f %12.9f %12.9f\n",
r[n][0],r[n][1],r[n][2],rv[n][0],rv[n][1],rv[n][2]);
}
Output: 输出:
0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000
0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000
0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000
Could anyone say what I'm doing wrong here? 有人可以说我在这里做错了吗?
As @BLUEPIXY says in the comments, you're telling fscanf
to parse your input values as float
s, but having it put them into double
s. 就像@BLUEPIXY在评论中说的,您要告诉fscanf
将输入值解析为float
,但是将其放入double
。 You could fix this by either (as suggested) use %lf
to tell fscanf
you're filling doubles, or declare r
and rv
to be arrays of float
s. 您可以通过(按照建议)使用%lf
告诉fscanf
您正在填充双精度数来解决此fscanf
,或者将r
和rv
声明为float
的数组。
Compilers are pretty good about warning of such things, if you ask them nicely. 如果您对它们的警告很好,那么编译器就可以很好地警告此类事情。
Your fscanf should look like : 您的fscanf应该如下所示:
fscanf(loadFile, "%lf %lf %f %lf %lf %lf",&r[n][0],&r[n][1],&r[n][2],&rv[n][0],&rv[n][1],&rv[n][2]);
Then delete the line 然后删除该行
fscanf(loadFile,"%d",&nAtom);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.