How does echoing works?

Hi guys.

I'm really curious about the echoing process in C++ because from my C++ Primer Plus book I can't really deduce how does it work. Author gives me this example:

1
2
3
4
5
6
7
cin >> ch;
while (ch != '#') // test for the stop char.
{
  cout << ch; // echo the char.
  ++count;
  cin >> ch;
}


Commentary isn't usefull at all. From my point of view this would happen after running this code:

1. Get character.
2. Test if this isn't or is #.
(if false)
3. Display the ch in next line.
4. Increment var.
5. Get new character and redo the loop.
(if true)
6. Abort the loop.

But somehow it works.
Please help me understand this correctly, because it isn't clear for me.

Thanks in advance.
Tobruk
Last edited on
cout will not output a new line unless you print a new line character '\n' (or use endl).
Perhaps these additional comments may help:

1
2
3
4
5
6
7
    cin >> ch;        // get next non-whitespace character
    while (ch != '#') // test for the stop char.
    {
         cout << ch;  // echo the char.
         ++count;
         cin >> ch;   // get next non-whitespace character
    }


The indicated lines discard whitespace until they come to a non-whitespace character.
When reading from a tty (a so called console on MS-Windows) echoing will usually (depending on your tty-settings) be done by the operating system while editing the line. After detecting the end of line sequence (usually newline, carriage return, or both of them) the line will be offered to the reading application process which in turn reads it character by character into the variable ch.
Line 6 does another echo.
Topic archived. No new replies allowed.