COMP104 : Quiz 8
 
File I/O

1. 	The following program is supposed to print out the contents of the file "data.dat" to the screen. 
What is wrong? 

	#include 
	#include 
	using namespace std;
	void main( ){
		ifstream fin;
		char next;
		fin.get(next);
		while(!fin.eof()){
			cout << next;
			fin.get(next);
		}
	}

 
Answer:	Open file "data.dat" before trying to read it, and close file.

	#include 
	#include 
	using namespace std;
	void main( ){
		ifstream fin;
		char next;
		fin.open("data.dat");
		fin.get(next);
		while(!fin.eof()){
			cout << next;
			fin.get(next);
		}
		fin.close();
	}


 
2.	The following program is supposed to print out the contents of the file "data.dat to the file "output.dat".
Correct any bugs.

	#include 
	#include 
	using namespace std;
	int main( ){
		ifstream fin;
		ofstream fout;
		int first, second, third;
	
		fin.open("data.dat");	
		cin >> first >> second >> third;
		cout << "The sum of the first 3"
 << "numbers in data.dat: "
		 << (first + second + third) 
 << endl;
		fin.close();
		return 0;
	}

 
Answer:	
1) Need to open the output file and close it
2) cin should be fin
3) cout should be fout


	int main( ){
		ifstream fin;
		ofstream fout;
		int first, second, third;
		
		fin.open("data.dat");
		fout.open("output.data");	
		fin >> first >> second >> third;
		fout << "The sum of the first 3"
 << "numbers in data.dat: "
		 << (first + second + third) 
 << endl;
		fin.close();
		fout.close();
		return 0;
	}