0

I wrote a program that supposed to print the number of characters that i entered till it hits the '#' character. what i don't understand is, when i input in the console more than one character (say "hello world") the program count all the characters in one iteration. why does it count all the character in one iteration instead of 1?

char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin.get(ch);
while (ch != '#')
{
    cout << ch;
    ++count;
    cin.get(ch); // use it again
}
cout << endl << count << " characters read\n";
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Ron Milich
  • 15
  • 2
  • As an aside, you should check whether the stream-state in the loop-condition. So, change it to: `std::cout << "prompt\n"; while (cin.get(ch) && ch != '#') { std::cout << ch; ++count; }`. – Deduplicator Oct 17 '18 at 19:55

1 Answers1

1

why does it count all the character in one iteration instead of 1?

It does not. You can verify that by changing the output a bit in the loop.

while (ch != '#')
{
   ++count;
   cout << "ch: " << ch << ", count: " << count << endl;
   cin.get(ch); // use it again
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270