cin.get(char)
to the Rescue
Usually, programs that read input character-by-character need to examine every character, including spaces, tabs, and newlines. The istream
class (defined in iostream
), to which cin
belongs, includes member functions that meet this need. In particular, the member function cin.get(ch)
reads the next character, even if it is a space, from the input and assigns it to the variable ch
. By replacing cin>>ch
with this function call, you can fix Listing 5.16. Listing 5.17 shows the result.
// textin2.cpp -- using cin.get(char)#include <iostream>int main(){ using namespace std; char ch; int count = 0; cout << "Enter characters; enter # to quit:\n"; cin.get(ch); // use the cin.get(ch) ...
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.