Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c++ - Reading and writing double precision from/to files

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
",(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
",ref[i], readIn[i]);
    }

  return 0;

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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

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;
 }

and

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

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].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...