CSCI 201 Study Aid: CIN

CIN

In C++, all input (and output for that matter) is accomplished with streams. The standard input stream object is cin (pronounced see-in), which is normally "connected" to the keyboard. The cin object is used in conjunction with the "stream extraction operator" >> to extract data values from the input stream.

Note: In order to use the cin object, you must include the iostream.h header file in your program. Attempting to use cin without including this file will result in linker errors.


Example 1:

The following program when run, will "prompt" the user for two numbers and will display their sum:


#include <iostream.h>

main()
{

int num1;
int num2;
int sum;

// Prompt for and accept the first number ...

cout << "Enter the first number: ";

cin >> num1;


// Prompt for and accept the second number ...

cout << "Enter the second number: ";

cin >> num2;


// Sum the two numbers and display result ...

sum = num1 + num2;

cout << "The sum of " << num1 << " and " << num2 << " is " << sum;


return 0;

}

In the previous program, the statement

   cin >> num1;

uses the input stream object cin and the stream extraction operators, >>, to obtain a value from the user. The cin object takes input from the standard input stream which is usually the keyboard. It is convenient to think of cin as "giving a value to num1".

When the computer executes the preceding statement, it waits for the user to enter a value for object num1. The user responds by typing an integer value and then pressing the return key to "send" the number to the computer. The computer then assigns this number, or value, to the object num1. Any subsequent references to num1 in the program will use this same value.


Example 2:

The example below uses cout to prompt the user to enter the number of hours worked and a wage. Note that the hours worked and wage are float objects to accommodate decimal numbers. The total pay is then calculated and displayed.


#include <iostream.h>

main()
{

float hours_worked;
float total_pay;
float wage;


// Prompt for and accept the hours worked ...

cout << "Enter the hours worked: ";

cin >> hours_worked;


// Prompt for and accept the wage per hour ...

cout << "Enter the wage: ";

cin >> wage;


// Calculate the total pay ...

total_pay = hours_worked * wage;

cout << "The total pay is $" << total_pay << endl;


return 0;

}