0

I took the following example literally from Walter Savitch Absolute C++ book. It works (as one would expect from a scholar such as Walter Savitch). However, I am puzzled why as I will explain after the code citation:

cout << "Enter a line of input and I will echo it:\n";
char symbol;
do
{
    cin.get(symbol);
    cout << symbol;
} while (symbol != '\n');
cout << "That's all for this demonstration.\n";

Possible output will look as follows:

Enter a line of input and I will echo it:
Do Be Do 1 2    34
Do Be Do 1 2    34
That's all for this demonstration.

My problem is the following. In going through the loop just once, cin.get(symbol) will find one character at a time, and cout will then output this one character consequently. Then, if my input wasn't a '\n' character, it will go into the loop for the second time, and so on, until finally the input equals '\n'.

However, in executing the code, all the input seems to be read at once, and then copied back at once. How can this happen if every input character needs to be checked to be equal to '\n'?

Final point, probably stating the obvious: this question does not pertain to code that is some way not syntactical. I am just puzzled about what happens during compilation and/or execution of the simple code I present above.

Hopefully someone can help me out!

Thanks.

Saro Taşciyan
  • 5,210
  • 5
  • 31
  • 50
Svalbard
  • 182
  • 2
  • 13

2 Answers2

0

Your observation is correct. It seems like all the input is read at once and then, printed out at once. The reason is that when the output is printed, it goes into a buffer which actually gets printed only when the buffer reaches a certain size, or whenever the code is all done. In the latter case, the output stream is closed and gets flushed. Practically speaking, this code is being printed but into a buffer.

unxnut
  • 8,509
  • 3
  • 27
  • 41
0

Well it looks like it's gettings handled at once, because it is. The loop is going on exactly as you've written - keeps on writing the char until it meets the end of line mark. There isn't really much logic behind it :)

Ghostli
  • 383
  • 1
  • 3
  • 11