ifstream reading integer problem

Joined
Nov 13, 2006
Messages
2
Reaction score
0
int main()
{
int i1 = 1, i2 = 2;
ofstream file("C:\\test.dat");
file<<i1<<i2;
file.close();

ifstream file1("C:\\test.dat");
file1>>i1;
file1.close();
cout<<i1<<endl;

}

the result is 12 not 1. Ints are wrote in byte by byte, but seems to be read out two bytes a time into i1 ? can anyone help me out?
 
Joined
Nov 9, 2006
Messages
3
Reaction score
0
Try this code...

#include <fstream>
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
int i1 = 1, i2 = 2;
ofstream file("C:\\test.dat");
file.write((char*)&i1,sizeof(i1));
file.write((char*)&i2,sizeof(i2));
//file<<i1<<i2;
file.close();

ifstream file1("C:\\test.dat");

int nNewL1,nNewL2;
file1.read((char*)&nNewL1,sizeof(nNewL1));
file1.read((char*)&nNewL2,sizeof(nNewL2));
//file1>>i1;
file1.close();
cout<<nNewL1<<endl;

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top