c++ - Reading and writing double precision from/to files -
i trying write double arrays files , read them again. below code, there missing. sounds silly cannot 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 (i = 0; < 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; }
your fscanf
using wrong format string (which gcc tell if enable sufficient warnings).
so double
filled float
value, of course leads rather "random" errors.
if change "%g"
"%lg"
, should work fine (at least on linux box).
of course, if use c++ streams, e.g.
#include <fstream> std::ofstream file1; std::ifstream file2; file1.open("output.txt"); (i = 0; < 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 have been avoided - , if edit readin
variable float
, long values valid that, possible read values without chaning else [assuming output using cout
instead of printf, of course].
Comments
Post a Comment