cin.get(char)
to the RescueUsually, 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:
";
cin.get(ch); // use the cin.get(ch) function
while (ch != '#')
{
cout << ch;
++count;
cin.get(ch); // use it again
}
cout << endl << count << " characters read
";
return 0;
}
Here is a sample run of the program in Listing 5.17:
Enter characters; enter # to quit:
Did you use a #2 pencil?
Did you use a
14 characters read
Now the program echoes and counts every character, including the spaces. Input is still buffered, so it is still possible to type more input than what eventually reaches the program.
If you are familiar with C, this program may strike you as terribly wrong. The cin.get(ch)
call places a value in the ch
variable, which means it alters the value of the variable. In C you must pass the address of a variable to a function if you want to change the value of that variable. But the call to cin.get()
in Listing 5.17 passes ch
, not &ch
. In C, code like this won’t work. In C++ it can work, provided that the function declares the argument as a reference. The reference type is something that C++ added to C. The iostream
header file declares the argument to cin.get(ch)
as a reference type, so this function can alter the value of its argument. You’ll learn the details in Chapter 8. Meanwhile, the C mavens among you can relax; ordinarily, argument passing in C++ works just as it does in C. For cin.get(ch)
, however, it doesn’t.
3.146.35.72