Programming Tutorials

Getting User Input Using cin in C++

By: Fazal in C++ Tutorials on 2007-09-17  

The global object cin is responsible for input and is made available to your program when you include iostream.h. In most of the examples in this site, you used the overloaded extraction operator (>>) to put data into your program's variables. How does this work? The syntax, as you may remember, is the following:

int someVariable;
cout << "Enter a number: ";
cin >> someVariable;

The global object cout is 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 cin has overloaded the extraction operator (>>) and that the effect is to write whatever data cin has in its buffer into your local variable, someVariable.

What may not be immediately obvious is that cin has overloaded the extraction operator 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 someVariable is assessed. In the example above, someVariable is 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 below illustrates the use of cin.

cin handles different data types.

1:     //character strings and cin
2:
3:     #include <iostream.h>
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;
15:       cout << "Long: ";
16:       cin >> myLong;
17:       cout << "Double: ";
18:       cin >> myDouble;
19:       cout << "Float: ";
20:       cin >> myFloat;
21:       cout << "Unsigned: ";
22:       cin >> myUnsigned;
23:
24:       cout << "\n\nInt:\t" << myInt << endl;
25:       cout << "Long:\t" << myLong << endl;
26:       cout << "Double:\t" << myDouble << endl;
27:       cout << "Float:\t" << myFloat << endl;
28:       cout << "Unsigned:\t" << myUnsigned << endl;
29:     return 0;
30: }

Output: int: 2
Long: 70000
Double: 987654321
Float: 3.33
Unsigned: 25

Int:    2
Long:   70000
Double: 9.87654e+08
Float:  3.33
Unsigned:       25

Analysis: On lines 7-11, variables of various types are declared. On lines 13-22, the user is prompted to enter values for these variables, and the results are printed (using cout) on lines 24-28.

The output reflects that the variables were put into the right "kinds" of variables, and the program works as you might expect.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)