Don't understand this cin/while loop example.

I'm reading a textbook (C++ Primer Plus by Stephen Prata) and currently at while loops and text input. He gives this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{

char ch;
cout << "Enter characters\n";
cin >> ch;

while (ch != '#'){

cout << ch;
cin >> ch;
}

}


What I don't understand is how cin knows to move to the next character. Is it that the first cin only stores 1 character (as char can only hold one) so whenever cin is repeated it reads the rest in the input stream?

Thanks!
1
2
3
4
5
while (ch != '#'){

cout << ch;
cin >> ch;
}


while the character is not equal to #

print out the character that was inputted

get input back in to ch from the user


The cin statement within the while loop will change the 'ch' variable to the new user input and then check it again to see whether ot not it is equal to # before deciding what to do.
Yes, every time the expression "cin >> ch" is evaluated, it reads (and stores in ch) the next character from the standard input stream, unless the stream has received the end-of-input sequence.

Note that the program will enter an endless loop if end-of-input happens (try entering Ctrl-D on Linux or Ctrl-Z on Windows)

That endless loop as well as some code repetition could be avoided with a for-loop:

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
int main()
{
    cout << "Enter characters\n";
    for(char ch; cin >> ch && ch != '#' ; )
        cout << ch;
}
Last edited on
Topic archived. No new replies allowed.