Chapter 8 - Cin Statement

The cin statement is used in programs to allow the user to enter a value for a variable while the program is running. This statement, like cout, is located in the iostream.h library. The following is an example cin statement:

cin >> Grapes;

When the program encounters this cin statement, the program pauses, waits for the user to enter a value on the keyboard, then stores this value in the variable Grapes. You will need to declare the variable Grapes before you do the cin statement. Notice that the cin statement is followed by two greater than signs >> while the cout statement is followed by two less than signs <<. It is good practice to precede a cin statement with a cout statement that lets the user know what they should enter. Below is the same cin statement, but this time with the variable declaration and a statement letting the user know what to enter.

cout << "Please enter the number of grapes you want to eat: ";
int Grapes;
cin >> Grapes;

Below is an example complete program using the cin statement. In the output of the program, we assume the user enters the number 20 when prompted.

Basic Cin Statement
#include <iostream> 
using namespace std;
int main()
{ 
   int Grapes; 
   cout << "How many grapes would you like to eat? "; 
   cin >> Grapes; 
   cout << "Why not eat this many: " << Grapes * 2 << endl; 
   return 0
}
How many grapes would you like to eat? 20
Why not eat this many: 40

If you use a cin statement to capture a string, it will truncate your input at the first space. To correct this, use a getline:

string S;
cout <<"Enter a sentence: ";
getline(cin,S);

The next program prompts the user for three variables then calculates the volume of a cube using these values. We assume the user enters the values 1.5, 2.8, and 3.7 for the dimensions.

Basic Cin Statement
#include <iostream> 
using namespace std; 
int main()
{ 
   cout << "This program calculates the volume of a cube.\n"; 
   float Base, Width, Height; 
   cout << "Enter the base: "; 
   cin >> Base; 
   cout << "Enter the width: "; 
   cin >> Width; 
   cout << "Enter the height: "; 
   cin >> Height; 
   cout << "The volume is: " << Base * Width * Height << endl; 
   return 0;
}
This program calculates the volume of a cube.
Enter the base: 1.5
Enter the width: 2.8
Enter the height: 3.7
The volume is: 15.54