cin / cout

Input (cin) / Output (cout):

Previously, you learned how to put data into variables using the assignment statement. In
this section, you will learn how to put data into variables from the standard input device,
using C++’s input (or read) statements.
When the computer gets the data from the keyboard, the user is said to be acting interactively.
Putting data into variables from the standard input device is accomplished via the use of
cin and the operator >>.

The syntax of cin together with >> is:
cin>>VARIABLE_NAME;
This is called an input (read) statement. In C++, >> is called the stream extraction
operator.


For Example:
Suppose that miles is a variable of type double. Further suppose that the input is
73.65.

Consider the following statements:
cin >> miles;
This statement causes the computer to get the input, which is 73.65, from the standard
input device and stores it in the variable miles. That is, after this statement executes, the
value of the variable miles is 73.65


Practice Program:
// Suppose we have the following statements:

int feet;
int inches;
Suppose the input is:
23 7
Next, consider the following statement:
cin >> feet >> inches;
This statement first stores the number 23 into the variable feet and then the number 7
into the variable inches. Notice that when these numbers are entered via the keyboard,
they are separated with a blank. In fact, they can be separated with one or more blanks or
lines or even the tab character.
The following C++ program shows the effect of the preceding input statements:
// This program illustrates how input statements work.
#include <iostream>
using namespace std;
int main()
{
int feet;
int inches;
cout << “Enter two integers separated by spaces: “;
cin >> feet >> inches;
cout << endl;
cout << “Feet = ” << feet << endl;
cout << “Inches = ” << inches << endl;
return 0;
}
Sample Run: In this sample run, the user input is shaded.
Enter two integers separated by spaces: 23 7
Feet = 23
Inches = 7

// This program illustrates how to read strings and numeric data.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string firstName; //Line 1
string lastName; //Line 2
int age; //Line 3
double weight; //Line 4
cout << “Enter first name, last name, age, “
<< “and weight, separated by spaces.”
<< endl; //Line 5
cin >> firstName >> lastName; //Line 6
cin >> age >> weight; //Line 7
cout << “Name: ” << firstName << ” “
<< lastName << endl; //Line 8
cout << “Age: ” << age << endl; //Line 9
cout << “Weight: ” << weight << endl; //Line 10
return 0; //Line 11
}
Sample Run: In this sample run, the user input is shaded.
Enter first name, last name, age, and weight, separated by spaces.
Sheila Mann 23 120.5
Name: Sheila Mann
Age: 23
Weight: 120.5