reading garbage using ifstream
Jan 24, 2014 at 8:30am UTC
Hi there..I have problem reading data from file...data is written correctly but after reading there is no change in variable where data is saved after reading..
compiler:DEV C++ 5.5.2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
unsigned int write,read=0;
cin>>write;
cout<<write;
ofstream writefile("data.txt" );
writefile<<write;
ifstream readfile("data.txt" );
if (readfile)
{
cout<<read<<endl;
readfile>>read;
cout<<read;
}
else
cout<<"unable to open file" ;
return 0;
}
if entered number is 5 lets say..5 will be written correctly wth this output
OUTPUT:
5
0
0
Last edited on Jan 24, 2014 at 8:36am UTC
Jan 24, 2014 at 9:14am UTC
Because
writefile and
readfile refer to the same file, you should close
writefile .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
#include <fstream>
#include <string>
using namespace std; // bad practice that you should unlearn
int main()
{
unsigned int write, read=0;
cout << "Give value of `write': " ;
cin >> write;
cout << "write is " << write << '\n' ;
ofstream writefile("data.txt" );
writefile << write;
writefile.close();
ifstream readfile("data.txt" );
if (readfile)
{
cout << "read is: " << read << '\n' ;
readfile >> read;
cout << "read is: " << read;
}
else
cout << "unable to open file\n" ;
return 0;
}
Last edited on Jan 24, 2014 at 9:16am UTC
Jan 24, 2014 at 9:19am UTC
Got it..thanks alot :)
Topic archived. No new replies allowed.