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.  It is good practice to precede a cin statement with a cout statement so that you can prompt the user for what they should enter.

Program 8a 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
}

Output
How many grapes would you like to eat? 20
Why not eat this many: 40

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. 

Program 8b Multiple Cin Statements

#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;
}

Output
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


Exercises Chapter 8

1.  Write a program that would have the following output: 

   Enter a number to convert from inches to centimeters: 4
   This is equal to 10.16 centimeters.
 

2.  Write a program that would have the following output:

   Enter your age: 21
   Enter your weight: 150
   You still have 79 years before you are 100.
   You can still gain 350 pounds before you weigh 500.