从/到文件读取和写入双精度 [英] Reading and writing double precision from/to files

查看:129
本文介绍了从/到文件读取和写入双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将双阵列写入文件并再次读取。下面是我的代码,但有一些我缺少的。这听起来很傻,但我不能得到它的权利。

I am trying to write double arrays into files and read them again. Below is my code, but there is something I am missing. It sounds silly but I cannot get it right.

#include <stdio.h>
#include <stdlib.h>

int main(){

  int i,j,k;
  int N = 10;

  double* readIn = new double[N];
  double* ref = new double[N];
  FILE* ptr1, *ptr2;

  ptr1 = fopen("output.txt","w");
  //write out
  for (i = 0; i < N;i++){
    ref[i] = (double)i;
    fprintf(ptr1,"%g\n",(double)i);
  }
  fclose(ptr1);
  //read file
  ptr2 = fopen("output.txt","r+");
  //read in
  for(i = 0;i < N;i++)
    fscanf(ptr2, "%g", &readIn[i]); 


  fclose(ptr2);

  for(i = 0;i<N;i++)
    if(ref[i] != readIn[i]){
      printf("Error:  %g   %g\n",ref[i], readIn[i]);
    }

  return 0;

}


推荐答案

code> fscanf 使用错误的格式字符串(GCC会告诉您如果启用足够的警告)。

Your fscanf is using the wrong format string (which GCC will tell you about if you enable sufficient warnings).

因此您的 double 填充了 float 这当然导致相当随机的错误。

So your double is filled with float value, which of course leads to rather "random" errors.

如果您将%g更改为%lg,它应该工作正常(至少它在我的Linux盒子上)。

If you change the "%g" to "%lg", it should work just fine (at least it does on my Linux box).

当然,如果你使用C ++流,例如。

Of course, if you use the C++ streams, e.g.

 #include <fstream>

 std::ofstream file1;
 std::ifstream file2;

 file1.open("output.txt");

 for (i = 0; i < N;i++){
    ref[i] = (double)i;
    file1 << (double)i << std::endl;
 }

   file2.open("output.txt");
   for(i = 0;i < N;i++)
      file2 >> readIn[i]; 

可以避免整个问题 - 如果你编辑 readIn 变量为 float ,只要这些值有效,就可以读取这些值而不改变任何其他值[假设输出也使用 cout 而不是printf,当然]。

the whole problem would have been avoided - and if you edit the readIn variable to be float, as long as the values are valid for that, it would be possible to read those values without chaning anything else [assuming the output is also using cout instead of printf, of course].

这篇关于从/到文件读取和写入双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆