You are on page 1of 11

cin >>

UNIT 8: INPUT STATEMENTS

Introduction

Data that we process are normally not part of our codes. Data for processing oftentimes
are inputted by the user or read from a file. We need to determine the types of data that will be
read or entered in order to make proper variable name declaration and initialization.

When asking user to input data, write a short prompt that will describe the data that
needs to be inputted. Without proper prompt, user may input the wrong type of data. Example:
with this prompt - Enter Section ( 1 – 5): the user will know that only numbers 1 to 5 are allowed.
But even with this prompt, user may sometimes accidentally press the wrong key on the
keyboard, so, it is a MUST to validate all the data that will be entered. Remember, GIGO!

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Use the keyboard t0 Input data.


2. Write proper input prompts.
3. Determine when to use cin >> and getline() function.

Course Materials:

8.1 cin statement

The usual input device in a computer is the keyboard. C++ cin statement is the
instance of the class istream and is used to read input from the standard input device which is
usually a keyboard. Again, you cannot use cin statement without #include<iostream> at
the start of your program.

The extraction operator (>>) is used together with the object cin for reading inputs. The
extraction operator extracts the data from the object cin which is entered using the keyboard.

>> are two greater than symbols with no space in between.

Before we can ask the user to input a data, you need to declare a variable that will store
the data. Make sure to use the right data type. For example, your data will be a whole number
then you must use int instead of double. int uses only four bytes of your memory while double
occupies eight bytes.

52
cin >>

Example 1

The program declares and initializes 3 int variables: curYear is given a value of 2020,
birthYear and age are both 0 since their values are not known during the creation of the
program. The value that will be entered by the user will be stored in birthYear and the
result of the computation will be stored in variable age.

Before the command, cin >> birthYear; we display a prompt by issuing the
command cout << "Enter your birth year: "; the user will now know what data to
enter.

#include <iostream>

using namespace std;

int main()
{
int curYear =2020, birthYear =0, age = 0;

cout << "Enter your birth year: ";


cin >> birthYear;
age = curYear - birthYear;
cout << "\n\nYour age is: " << age;

return 0;
}

53
cin >>

Now, let us delete the line cout << "Enter your birth year: "; the program
will still run but the user will have no idea what to enter or press.

#include <iostream>

using namespace std;

int main()
{
int curYear =2020, birthYear =0, age = 0;

cin >> birthYear;


age = curYear - birthYear;
cout << "\n\nYour age is: " << age;

return 0;
}

When you run the program the initial screen will be like this:

There is only a blinking cursor on the first line, waiting for you to enter something. The
user unless he is the one who created the program will know what data to entered, if not, the will
be confused he might think there is something wrong with the program or will wait for something
to appear on the screen.

54
cin >>

If I press a letter, this will be the output.

Example 2

The program below will compute the salary of an employee based on the value of hours
worked and hourly rate entered. The value of tax rate is 20%. When you initialize a variable it
is not always zero or blank it can be another value, depending on the requirements of the
program.

You can also make taxRate as constant ( const float taxRate = 0.20;) Make
use of proper indentions and spacing to make your program more readable.

#include <iostream>
using namespace std;

int main()
{
// variable declaration and initialization
float taxRate = 0.20;
int hWork = 0;
float hRate = 0.0;
float gross = 0.0;
float tax = 0.0;
float salary = 0.0;

// data entry
cout << "Enter number of working hours: ";
cin >> hWork;
cout << "Enter hourly rate: ";

55
cin >>

cin >> hRate;

// computation
gross = hWork * hRate;
tax = gross * taxRate;
salary = gross - tax;

// display output
cout << "\n\nGross pay: " << gross;
cout << "\n Tax: " << tax;
cout << "\n Salary: " << salary;

return 0;
}

8.2 How to input string

String data type can be composed of more than one character. A character can be a
letter in lowercase (a-z) or uppercase (A-Z) , a digit (0 – 9), or a special character or symbol.
So, a string can be a combination of those characters. Aside from cin >> we can also use the
function getline(). Observe their difference when you run the program below.

Example 3

We use the program in Example 2 but added a string variable and another prompt and
cin statement. The program will run smoothly if the name you entered has no space in between
them.

56
cin >>

#include <iostream>
using namespace std;

int main()
{
// variable declaration and initialization
int hWork = 0;
float hRate = 0.0;
float gross = 0.0;
float tax = 0.0;
float taxRate = 0.20;
float salary =0.0;
string empName = "";

// data entry
cout << "Enter name of employee: ";
cin >> empName;
cout << "Enter number of working hours: ";
cin >> hWork;
cout << "Enter hourly rate: ";
cin >> hRate;

// computation
gross = hWork * hRate;
tax = gross * taxRate;
salary = gross - tax;

// display output
cout << "\n\n Employee: " << empName;
cout << "\nGross pay: " << gross;
cout << "\n Tax: " << tax;
cout << "\n Salary: " << salary;

return 0;
}

57
cin >>

Now, let us try inputting the whole name ex. Cardo Dalisay. This will be the outcome:

When you type Cardo Dalisay and then press the Enter key, the program will not ask
you anymore to enter the values for hours worked and hourly rate. Why? Using cin >> will only
read up to the first space it encounters. Thus, employee name is only Cardo, it ignores the
characters after the space (Dalisay). Those characters ignored are passed to the other variables
and since they are not numeric value they will consider them as zero.

Solution:

Instead of using cin>> empName; replace it with getline(cin, empName); the


function getline() will read up to last character before you press the Enter key. So we can
say that for string, cin>> looks for the space and getline() looks for the Enter key.

#include <iostream>
#include <string>
using namespace std;

int main()
{
// variable declaration and initialization
int hWork = 0;
float hRate = 0.0;
float gross = 0.0;
float tax = 0.0;
float taxRate = 0.20;
float salary =0.0;
string empName = "";

// data entry
cout << "Enter name of employee: ";
getline(cin,empName);
cout << "Enter number of working hours: ";

58
cin >>

cin >> hWork;


cout << "Enter hourly rate: ";
cin >> hRate;

// computation
gross = hWork * hRate;
tax = gross * taxRate;
salary = gross - tax;

// display output
cout << "\n\n Employee: " << empName;
cout << "\nGross pay: " << gross;
cout << "\n Tax: " << tax;
cout << "\n Salary: " << salary;

return 0;
}

The syntax of getline() function is getline(cin, stringVariable); and at the


beginning of the program add #include <string> because the codes for getline() function is
in this header file.

Note: To be safe use getline() function when asking for data of type string and cin>> for
numbers char and other data types.

59
cin >>

Example 4

This program will ask the user to enter the name, section (char type), grades in first and
second grading, then compute and display the final grade of the student.

#include <iostream>
#include <string>
using namespace std;
int main()
{
// variable declaration and initialization
string studName = "";
char studSection = ' ';
float firstGrading = 0.0;
float secGrading = 0.0;
float finGrade = 0.0;

// data entry
cout << "Enter name of student: ";
getline(cin, studName);
cout << "Enter section (A-F): ";
cin >> studSection;
cout << "Enter grade during first grading: ";
cin >> firstGrading;
cout << "Enter grade during second grading: ";
cin >> secGrading;

// computation
finGrade = (firstGrading + secGrading)/2;

// display output
cout << "\n\n Student: " << studName;
cout << "\n Section: " << studSection;
cout << "\n\n Final Grade: " << finGrade;

return 0;
}

60
cin >>

Activities

Write program lines to display prompt and allow user to enter the data.

1. Number of students enrolled in first year.


2. Name of hospital
3. Percentage of population affected by covid-19
4. Delivery charge for item ordered online
5. Floor area of a house

Programming

1. Write a C++ program that asks the user to enter two numbers, obtains the two numbers
from the user, and prints the sum, product, difference and quotient of the two numbers.

2. Write a C++ program that asks the user to enter the number of miles driven and gallons
used for each full tank. The program should calculate and display the miles per gallon
obtained for each full tank.

3. Write a C++ program that will compute and display the take home pay of an employee.
You need to enter the name of the employee, the total number of hours worked, the
hourly rate and the tax rate.

4. A salesperson needs to compute the number of tiles a customer should buy. The
salesperson must know the length and width of the floor in meters and the size of the tile

61
cin >>

(length and width in centimeter) the customer chose to buy. Write a C++ program to
accomplish this task.

5. How much must a senior citizen pay for the medicines he/she bought if all requirements
are presented to the drugstore? The program must ask the user to enter the total cost of
medicines. Compute and display the discounts and the amount to be paid by the senior.
(Philippine setting – do some research  )

Online References

http://www.cplusplus.com/reference/iostream/cin/

https://www.w3schools.com/cpp/cpp_user_input.asp

https://www.learncpp.com/cpp-tutorial/introduction-to-iostream-cout-cin-and-endl/

62

You might also like