Why does this code work?

Hi, I was reading a book and I came across this code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>


int main()
{
    using namespace std;
    cout << "Enter characters; enter # to quit: ";
    char ch;
    int count = 0;
    cin >> ch;
    while (ch != '#')
    {
        cout << ch;
        ++count;
        cin >> ch;
    }
    cout << endl << count << " characters read\n";
    return 0;
}


I enter a sentence : Hello, how#are you?
It displays Hello,how

I thought a char variable could only hold one character at a time if it was not an array?
You're right. But, you are looping and reading another character with "cin >> ch", until ch == '#'.
Last edited on
cin reads from a special file called Standard Input.
Even if you give a full sentence in one go, the program will still read it character by character.
Topic archived. No new replies allowed.