c++ - How do I read a double from file? -


i came following code:

#include <stdio.h> #include <iostream> #include <fstream>  int main() {   std::ifstream a0;   a0.open("data/a0", std::ios::in | std::ios::binary);   double d;   a0 >> d;   printf("%e\n", d); } 

i compile with

g++ -s -wall -wextra -pedantic -std=c++0x -o program program.cpp 

but doesn't work - prints 0 (the actual first 8 bytes of file 3d 8f a0 bb e0 00 00 00). more interesting, when data/a0 file doesn't exist, garbage output, if file exist, output strictly 0.

what doing wrong?

if file binary, must use unformatted input functions it:

double d; if (!a0.read(reinterpret_cast<char*>(&d), sizeof(d))) {   // error occurred } std::cout << d << '\n'; 

operator >> formatted input, means expects text in file.

edit

sorry, used get() instead of read(), more useful reading text files in binary format.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -