Why does this program only print when there's a newline?

Hi,

I've written a program to calculate RAM usage on a Linux machine, and I've experienced some strange behavior trying to output the results. The code is as follows:

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
int main()
{
	ifstream reader("/proc/meminfo", ios::in);
	if(! reader)
	{
		cout << "Error opening /proc/meminfo\n";
		return -1;
	}

	int memTotal, memFree, memUsed;
	while(1)
	{
		string memTotalStr;
		getline(reader, memTotalStr);
		memTotal = convert(removeText(memTotalStr));

		string memFreeStr;
		getline(reader, memFreeStr);
		memFree = convert(removeText(memFreeStr));

		memUsed = memTotal - memFree;

		cout.precision(2);
		cout << float(memUsed) / 1048576.0 << "GB / " << float(memTotal) / 1048576.0 << "GB";
		cout << "\t" << float(memUsed) / float(memTotal) * 100.0 << "%\n";

		reader.seekg(0);
		sleep(1);
	}
	return 0;
}


And this works fine. However, I want to change the output so it's on one line, which I believe would be done through the /r escape character. I had a go, and found that it didn't work. Upon looking further, I found that removing \n from line 25 makes the program print nothing, it just sits in the loop forever. This happened even when there were no \r or any other escape characters in the program. Adding it back (or endl) and it printed again.

What's going on here?
Did you try cout.flush(); after your output?
Last edited on
Thanks, that's works great. Would you be able to explain why it does, I'm still confused.
Glad it was useful.

The output stream is buffered. That makes a lot of sense with for example a disk file, instead of writing one character at a time, the data is cached in a buffer until it is full, then the whole lot is written at once.

In the case of output to the console, the endl code automatically flushes the buffer (that is, forces it to write out the contents, even if the buffer is not full). In the case of the newline character '\n', I wasn't quite sure, I know this can sometimes force the emptying of the buffer too.
Oh ok, that makes sense. Thanks again.
Topic archived. No new replies allowed.