I need to serialize a int to local file and read it into memory. Here is the code
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int _tmain ( int argc, _TCHAR* argv[] )
{
ofstream fileout;
fileout.open ( "data,txt" );
fileout << 99999999;
fileout << 1;
cout << fileout.tellp() << endl;
fileout.flush();
fileout.close();
ifstream fileint;
fileint.open ( "data,txt" );
int i, a;
fileint >> i >> a; //i != 99999999 a!= 1 WHY?
cout << fileint.tellg() << endl;
return 0;
}
but it doesn’t work right, I can’t get i==99999999 or a==1. What is wrong with that?
The problem is that
operator <<andoperator >>are not duals —operator <<outputs things directly with no padding or delimeters, whileoperator >>parses whitespace delimited input. So you need to manually add whitespace delimiters between things in your output to have it read back properly. You also can’t output things that contain whitespace and expect to have them read back properly.