Practical 6

These exercises all extend exercise 3 from practical 4. One possible solution is available here.

Examples of file input and output as given in the lecture are here.

Exercise 1

Exercise 2

Writing to a file is very easy in C++, here is a program to write a test file,

#include <fstream>

int main()

{
	std::ofstream out("test.txt");
	for (int i=1; i<10; i++)

	{
		for (int j=0; j<i; j++)
			out << "*";
		out << " " << i << std::endl;
	}

	out.close();
	return(0);
}

Exercise 3

Reading from a file is also easy, here is a program to read a file,

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main()
{
	ifstream in("test.txt");
	string stars;
	int num;

	while(in >> stars >> num)

	{
		cout << num << ": " << stars << endl;
	}
	in.close();

	return(0);

}