No new exercises for this week, complete and enhance the exercises from last week. You might also wish to spend some time experimenting with the use of pointers, structures and functions.
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);
}
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);
}
The function clock() is declared in the <ctime> header file. This will give the time elapsed since the program
started to run. This time must be converted to seconds by dividing by the constant CLOCKS_PER_SEC. The following program will run for two minutes and then stop.
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
cout << "Please wait for two minutes...";
while((clock()/CLOCKS_PER_SEC < 120))
{
// do something here !
}
return 0;
}