Working with Streams 599
17
Input Using cin....................................................................................................
The global object cinis responsible for input and is made available to your program
when you include iostream. In previous examples, you used the overloaded extraction
operator (>>) to put data into your program’s variables. How does this work? The syntax,
as you might remember, is as follows:
int someVariable;
cout << “Enter a number: “;
cin >> someVariable;
The global object coutis discussed later today; for now, focus on the third line,cin >>
someVariable;. What can you guess about cin?
Clearly, it must be a global object because you didn’t define it in your own code. You
know from previous operator experience that cinhas overloaded the extraction operator
(>>) and that the effect is to write whatever data cinhas in its buffer into your local vari-
able,someVariable.
What might not be immediately obvious is that cinhas overloaded the extraction opera-
tor for a great variety of parameters, among them int&,short&,long&,double&,float&,
char&,char*, and so forth. When you write cin >> someVariable;, the type of
someVariableis assessed. In the preceding example,someVariableis an integer, so the
following function is called:
istream & operator>> (int &)
Note that because the parameter is passed by reference, the extraction operator is able to
act on the original variable. Listing 17.1 illustrates the use of cin.
LISTING17.1 cinHandles Different Data Types
0: //Listing 17.1 - character strings and cin
1:
2: #include <iostream>
3: using namespace std;
4:
5: int main()
6: {
7: int myInt;
8: long myLong;
9: double myDouble;
10: float myFloat;
11: unsigned int myUnsigned;
12:
13: cout << “Int: “;
14: cin >> myInt;