Flush and I/O Buffering

Here are two examples of strange behavior:

#include <iostream>
using namespace std;

int main()
{
	cout << "Got here ...";
	int* A = 0;
	A[0] = 25;
	cout << " and now I'm here!" << endl;
	return 0;
}
When I run this, I expect to see Got here ..., and then see a Seg Fault message. Here's what I get instead:
~/$ ./prog 
Segmentation fault (core dumped)

Q: What happened to the "Got here" message?


#include <iostream>
#include <unistd.h>
using namespace std;

int main()
{
  for(int i = 0; i < 10; i++)
  {
    cout << '*';
    sleep(1);
  }
  cout << endl;
  return 0;
}
When I run this, I expect to see a *, then one second later see another *, then one second later see another *, and so on until 10 *'s are printed.

Q: Instead, I see nothing for 10 whole seconds, then all at once I see 10 *'s. What's happening?

The answer in both cases is I/O bufferring is happening. When you write things with cout, the characters you write are "bufferred", that means stored temporarily until either enough have been collected to make writing to the screen worthwhile, or some event has occurred to cause the less-than-full buffer to be written to the screen despite having unused capacity. Such events include:

We've seen these events but the last one. The last event "flushes the buffer", i.e. forces the contents of the buffer to be written to the screen, without writing a newline. Using this, we can get the second example working as we'd like:

#include <iostream>
#include <unistd.h>
using namespace std;

int main()
{
  for(int i = 0; i < 10; i++)
  {
    cout << '*' << flush;
    sleep(1);
  }
  cout << endl;
  return 0;
}

2D Array Practice

Here's a good problem to work on, as it takes into account a number of the things we've talked about: The file scores.txt contains the scores of students on various problems on an exam. Each row corresponds to a student, and the scores along that row are that student's scores on problems 1, 2, 3 etc.

Your job: figure out which problem was the hardest!

You may assume that for every problem, at least one student got full credit for that problem. If the average score for problem X as a percentage of the full credit score for X is less than the average score for problem Y as a percentage of the full credit score for Y, then problem X is "harder" than problem Y.


~/$ ./prob1
Problem p4 is hardest (ave = 48.5294%)
Check out this solution.