我需要将int序列化为本地文件并将其读入内存.这是代码
#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;
}
Run Code Online (Sandbox Code Playgroud)
但它不能正常工作,我无法得到i == 99999999或a == 1.这有什么问题?
问题是,operator <<并且operator >>不是双重 - operator <<直接输出事物,没有填充或分隔符,同时operator >>解析空格分隔的输入.因此,您需要在输出中的事物之间手动添加空白分隔符,以使其正确读回.您也无法输出包含空格的内容并期望正确读回.