0% found this document useful (0 votes)
8 views55 pages

Chapter 03

Uploaded by

kayistuana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views55 pages

Chapter 03

Uploaded by

kayistuana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 55

C++ Programming:

Program Design Including


Data Structures, Third Edition

Chapter 3: Input/Output
Objectives

In this chapter you will:


• Learn what a stream is and examine input
and output streams
• Explore how to read data from the standard
input device
• Learn how to use predefined functions in a
program
• Explore how to use the input stream functions
get, ignore, fill, putback, and peek

C++ Programming: From Problem Analysis to Program Design, Third Edition 2


Objectives (continued)

• Become familiar with input failure


• Learn how to write data to the standard
output device
• Discover how to use manipulators in a
program to format output
• Learn how to perform input and output
operations with the string data type
• Become familiar with file input and output

C++ Programming: From Problem Analysis to Program Design, Third Edition 3


Input/Output Streams

• I/O: sequence of bytes (stream of bytes) from


source to destination
• Bytes are usually characters, unless program
requires other types of information
• Stream: sequence of characters from source
to destination
• Input Stream: sequence of characters from
an input device to the computer
• Output Stream: sequence of characters from
the computer to an output device
C++ Programming: From Problem Analysis to Program Design, Third Edition 4
Standard I/O Devices
• Use iostream to extract (receive) data from
keyboard and send output to the screen
• iostream header file contains, among other
things, the definitions of two data types,
− istream - input stream
− ostream - output stream
• iostream header also contains two variable
− cin - stands for common input
− cout - stands for common output

C++ Programming: From Problem Analysis to Program Design, Third Edition 5


Using cin and cout

• To use cin and cout, the preprocessor


directive #include <iostream> must be
used
• The declaration is similar to the following C++
statements:
istream cin;
ostream cout;
• Input stream variables: type istream
• Output stream variables: type ostream
C++ Programming: From Problem Analysis to Program Design, Third Edition 6
cin and the Extraction Operator
>>
• The syntax of an input statement using cin
and the extraction operator >> is
cin >> variable >> variable...;

• The extraction operator >> is binary


• The left-hand operand is an input stream
variable such as cin
• The right-hand operand is a variable of a
simple data type
C++ Programming: From Problem Analysis to Program Design, Third Edition 7
Standard Input
• Every occurrence of >> extracts the next data
item from the input stream
• Two variables can be read using a single cin
statement
• No difference between a single cin with
multiple variables and multiple cin statements
with one variable
• When scanning, >> skips all whitespace
• Whitespace characters consist of blanks and
certain nonprintable characters
C++ Programming: From Problem Analysis to Program Design, Third Edition 8
Data Type of Input
• >> distinguishes between character 2 and
number 2 by the right hand operand of >>
− If it is of type char, the 2 is treated as character
2
− If it is of the type int (or double) the 2 is
treated as the number 2

C++ Programming: From Problem Analysis to Program Design, Third Edition 9


Reading Data

• When reading data into a char variable

− Extraction operator >> skips leading


whitespace, finds and stores only the next
character

− Reading stops after a single character

C++ Programming: From Problem Analysis to Program Design, Third Edition 11


Reading Data (Continued)

• To read data into an int or double variable

− Extraction operator >> skips leading


whitespace, reads plus or minus sign (if any),
reads the digits (including decimal)

− Reading stops on whitespace non-digit


character

C++ Programming: From Problem Analysis to Program Design, Third Edition 12


Example 3-1
int a, b;
double z;
char ch, ch1, ch2;

Statement Input Value Stored in Memory

1 cin >> ch; A ch = 'A‘

2 cin >> ch; AB ch = 'A', 'B' is held for later

input

3 cin >> a; 48 a = 48

4 cin >> a; 46.35 a = 46, .35 is held for later


input

5 cin >> z; 74.35 z = 74.35

6 cin >> z; 39 z = 39.0

7 cin >> z >> a; 65.78 38 z = 65.78, a = 38


Statement Input Value Stored in Memory

8 cin >> a >> b; 4 60 a = 4, b = 60

9 cin >> a >> ch >> z; 57 A 26.9 a = 57, ch = 'A', z = 26.9

10 cin >> a >> ch >> z; 57 A26.9 a = 57, ch = 'A', z = 26.9

11 cin >> a >> ch >> z; 57 A26.9 a = 57, ch = 'A', z = 26.9

12 cin >> a >> ch >> z; 57A26.9 a = 57, ch = 'A', z = 26.9

13 cin >> z >> ch >> a; 36.78B34 z = 36.78, ch = 'B', a = 34

14 cin >> z >> ch >> a; 36.78 B34 z = 36.78, ch = 'B', a = 34

15 cin >> a >> b >> z; 11 34 a = 11, b = 34, computer waits


for

the next number


Statement Input Value Stored in Memory

16 cin >> a >> z; 46 32.4 68 a = 46, z = 32.4,

68 is held for later input

17 cin >> a >> z; 78.49 a = 78, z = 0.49

18 cin >> ch >> a; 256 ch = '2', a = 56

19 cin >> a >> ch; 256 a = 256, computer waits for the

input value for ch

20 cin >> ch1 >> ch2; AB ch1 = 'A', ch2 = 'B‘

21 cin >> a >> ch >> z; 57A26.9 a = 57 ch = 'A', z = 26.9

22 cin >> a >> z; 78.49 a = 78, z = 0.49

23 cin >> ch >> a; 256 ch = '2', a = 56


Using Predefined Functions

• A function (subprogram): set of instructions


• When activated, it accomplishes a task
• main executes when a program is run
• Other functions execute only when called
• C++ includes a wealth of functions
• Predefined functions are organized as a
collection of libraries called header files

C++ Programming: From Problem Analysis to Program Design, Third Edition 16


Predefined Functions

• Header file may contain several functions


• To use a predefined function, you need the
name of the appropriate header file
• You also need to know:
− Function name
− Number of parameters required
− Type of each parameter
− What the function is going to do
C++ Programming: From Problem Analysis to Program Design, Third Edition 17
Predefined Function Example

• To use pow (power), include cmath

• pow has two numeric parameters

• The syntax is: pow(x,y) = xy

• x and y are the arguments or parameters

• In pow(2,3), the parameters are 2 and 3

C++ Programming: From Problem Analysis to Program Design, Third Edition 18


Example 3-2
//How to use predefined functions.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
double u, v;
string str;
cout << "Line 1: 2 to the power of 6 = "
<< pow(2.0, 6.0) << endl; //Line 1
u = 12.5; //Line 2
v = 3.0; //Line 3
cout << "Line 4: " << u
<< " to the power of "
<< v << " = " << pow(u, v)
<< endl; //Line 4
cout << "Line 5: Square root of 24 = "
<< sqrt(24.0) << endl; //Line 5
u = pow(8.0, 2.5); //Line 6
cout << "Line 7: u = " << u
<< endl; //Line 7
str = "Programming with C++"; //Line 8
cout << "Line 9: Length of str = "
<< str.length() << endl; //Line 9
return 0;
}

Sample Run:
Line 1: 2 to the power of 6 = 64
Line 4: 12.5 to the power of 3 = 1953.13
Line 5: Square root of 24 = 4.89898
Line 7: u = 181.019
Line 9: Length of str = 20
cin and the get Function
• The variable cin can access the stream function get, which is
used to read character data. The get function inputs the very
next character, including whitespace characters, from the input
stream and stores it in the memory location indicated by its
argument.
• The get function
− Inputs next character (including whitespace)
− Stores character location indicated by its argument
• The syntax of cin and the get function:
cin.get(varChar);
varChar
− Is a char variable
− Is the argument (parameter) of the function

C++ Programming: From Problem Analysis to Program Design, Third Edition 21


cin and the get Function
• As you have seen, the extraction operator skips all leading
whitespace characters when scanning for the next input value.
Consider the variable declarations:
• char ch1, ch2; int num;
• and the input:
• A 25
• Now consider the following statement:
• cin >> ch1 >> ch2 >> num;
• When the computer executes this statement, 'A' is stored in ch1, the
blank is skipped by the extraction operator >>, the character '2' is
stored in ch2, and 5 is stored in num. However, what if you intended
to store 'A' in ch1, the blank in ch2, and 25 in num? It is clear that
you cannot use the extraction operator >> to input this data.

C++ Programming: From Problem Analysis to Program Design, Third Edition 22


cin and the get Function

• Now consider the following input again:


• A 25
• To store 'A' in ch1, the blank in ch2, and 25 in
num, you can effectively use the get function
as follows:
• cin.get(ch1);
• cin.get(ch2);
• cin >> num;

C++ Programming: From Problem Analysis to Program Design, Third Edition 23


cin and the ignore Function

• ignore: discards a portion of the input


• The syntax to use the function ignore is:
cin.ignore(intExp, chExp);
intExp is an integer expression
chExp is a char expression
• If intExp is a value m, the statement says to
ignore the next m characters or all characters
until the character specified by chExp
C++ Programming: From Problem Analysis to Program Design, Third Edition 24
cin and the ignore Function
• cin.ignore(100, '\n');
• When this statement executes, it ignores either the next 100
characters or all characters until the newline character is found,
whichever comes first. For example, if the next 120 characters
do not contain the newline character, then only the first 100
characters are discarded and the next input data is the
character 101. However, if the 75th character is the newline
character, then the first 75 characters are discarded and the
next input data is the 76th character. Similarly, the execution of
the statement:
• cin.ignore(100, 'A');
• results in ignoring the first 100 characters or all characters until
the character 'A' is found, whichever comes first.

C++ Programming: From Problem Analysis to Program Design, Third Edition 25


cin and the ignore Function
• Consider the declaration:
int a, b;
and the input:
25 67 89 43 72
12 78 34
• Now consider the following statements:
cin >> a; cin.ignore(100, '\n'); cin >> b;
• The first statement, cin >> a;, stores 25 in a. The second
statement, cin.ignore(100, '\n');, discards all of the
remaining numbers in the first line. The third statement,
cin >> b;, stores 12 (from the next line) in b.

C++ Programming: From Problem Analysis to Program Design, Third Edition 26


cin and the ignore Function
• Consider the declaration:
• char ch1, ch2;
• and the input:
• Hello there. My name is Mickey.
• Consider the following statements:
• cin >> ch1; cin.ignore(100, '.'); cin >> ch2;
• The first statement, cin >> ch1;, stores'H' in ch1. The second
statement, cin.ignore(100, '.');, results in discarding all
characters until . (period). The third statement, cin >> ch2;,
stores the character'M' (from the same line) in ch2. (Remember
that the extraction operator >> skips all leading whitespace
characters. Thus, the extraction operator skips the space after .
[period] and stores 'M' in ch2.)

C++ Programming: From Problem Analysis to Program Design, Third Edition 27


putback and peek Functions

• putback function
− Places previous character extracted by the
get function from an input stream back to that
stream
• peek function
− Returns next character from the input stream
− Does not remove the character from that
stream

C++ Programming: From Problem Analysis to Program Design, Third Edition 28


EXAMPLE 3-7
//Functions peek and putback
#include <iostream>
using namespace std;
int main() {
char ch;
cout << "Enter a string: ";
cin.get(ch);
cout << endl;
cout << "After first cin.get(ch); " << "ch = " << ch << endl;
cin.get(ch);
cout << "After second cin.get(ch); " << "ch = " << ch << endl;
cin.putback(ch);
cin.get(ch);
cout << "After putback and then " << "cin.get(ch); ch = " << ch << endl;
ch = cin.peek();
cout << After cin.peek(); ch = " << ch << endl;
cin.get(ch);
cout << "After cin.get(ch); ch = " << ch << endl;
}

C++ Programming: From Problem Analysis to Program Design, Third Edition 29


putback and peek Functions
(continued)
• The syntax for putback:
− istreamVar.putback(ch);
− istreamVar - an input stream variable, such
as cin
− ch is a char variable
• The syntax for peek:
− ch = istreamVar.peek();
− istreamVar is an input stream variable (cin)
− ch is a char variable
C++ Programming: From Problem Analysis to Program Design, Third Edition 30
Dot Notation

• In the statement
cin.get(ch);

cin and get are two separate identifiers


separated by a dot
• Dot separates the input stream variable name
from the member, or function, name
• In C++, dot is the member access operator

C++ Programming: From Problem Analysis to Program Design, Third Edition 31


Input Failure

• Things can go wrong during execution


• If input data does not match the
corresponding variables, the program may
run into problems
• Trying to read a letter into an int or double
variable would result in an input failure
• If an error occurs when reading data
− Input stream enters the fail state

C++ Programming: From Problem Analysis to Program Design, Third Edition 32


Input Failure (continued)

• Once in a fail state, all further I/O statements


using that stream are ignored
• The program continues to execute with
whatever values are stored in variables
• This causes incorrect results
• The clear function restores input stream to
a working state
istreamVar.clear();

C++ Programming: From Problem Analysis to Program Design, Third Edition 33


Writing to Standard Output

• Syntax of cout when used with <<


cout < <expression or manipulator
<< expression or manipulator...;

• Expression is evaluated
• Value is printed
• Manipulator is used to format the output

C++ Programming: From Problem Analysis to Program Design, Third Edition 34


Formatting Output

• endl manipulator moves output to the


beginning of the next line
• setprecision(n) outputs decimal
numbers with up to n decimal places
• fixed outputs floating-point numbers in a
fixed decimal format
• showpoint forces output to show the
decimal point

C++ Programming: From Problem Analysis to Program Design, Third Edition 35


//Example: scientific and fixed
#include <iostream>
using namespace std;
int main() {
double hours = 35.45;
double rate = 15.00;
double tolerance = 0.01000;
cout << "hours = " << hours << ", rate = " << rate << ", pay = " << hours * rate << ", tolerance
= " << tolerance << endl << endl;
cout << scientific;
cout << "Scientific notation: " << endl;
cout << "hours = " << hours << ", rate = " << rate << ", pay = " << hours * rate << ", tolerance
= " << tolerance << endl << endl;
cout << fixed;
cout << "Fixed decimal notation: " << endl; cout << "hours = " << hours << ", rate = " << rate
<< ", pay = " << hours * rate << ", tolerance = " << tolerance << endl << endl;
}

C++ Programming: From Problem Analysis to Program Design, Third Edition 36


The setw Manipulator
setw outputs the value of an expression in specific columns
If the number of columns exceeds the number of columns required
by the expression
− Output of the expression is right-justified
− Unused columns to the left are filled with spaces
For example, if x is an int variable, the following statement
outputs the value of x in five columns on the standard output
device:
− cout << setw(5) << x << endl;
To use the manipulator setw, the program must include the
header file iomanip.

C++ Programming: From Problem Analysis to Program Design, Third Edition 37


Additional Output Formatting
Tools
• Output stream variables can use setfill to
fill unused columns with a character
• left: left-justifies the output
− ostreamVar << left;

• Disable left by using unsetf


• right: right-justifies the output
− ostreamVar << right;
C++ Programming: From Problem Analysis to Program Design, Third Edition 38
Types of Manipulators

• Two types of manipulators:


− With parameters
− Without parameters
• Parameterized: require iomanip header
− setprecision, setw, and setfill
• Nonparameterized: require iostream
header
− endl, fixed, showpoint, and left

C++ Programming: From Problem Analysis to Program Design, Third Edition 39


I/O and the string Type
• An input stream variable (cin) and extraction
operator >> can read a string into a variable of
the data type string
• Extraction operator
− Skips any leading whitespace characters and
reading stops at a whitespace character
− Should not be used to read strings with blanks
• The function getline
− Reads until end of the current line
− Should be used to read strings with blanks
C++ Programming: From Problem Analysis to Program Design, Third Edition 40
Programming Example

• A theater owner agrees to donate a portion of


gross ticket sales to a charity
• The program will prompt the user to input:
− movie name
− adult ticket price
− child ticket price
− number of adult tickets sold
− number of child tickets sold
− percentage of gross amount to be donated
C++ Programming: From Problem Analysis to Program Design, Third Edition 41
Programming Example I/O

• Inputs: movie name, adult and child ticket


price, # adult and child tickets sold, and
percentage of the gross to be donated
• Program output:
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Movie Name: ..................Duckey Goes to Mars
Number of Tickets Sold: ........... 2650
Gross Amount: ..................... $ 9150.00
Percentage of Gross Amount Donated: 10.00%
Amount Donated: ................... $ 915.00
Net Sale: ......................... $ 8235.00
C++ Programming: From Problem Analysis to Program Design, Third Edition 42
Problem Analysis

• The program needs to:

1. Get the movie name

2. Get the price of an adult ticket price

3. Get the price of a child ticket price

4. Get the number of adult tickets sold

5. Get the number of child tickets sold

C++ Programming: From Problem Analysis to Program Design, Third Edition 43


Problem Analysis (continued)

6. Get the percentage of the gross amount


donated to the charity

7. Calculate the gross amount

8. Calculate the amount donated to the charity

9. Calculate the net sale amount

10. Output the results

C++ Programming: From Problem Analysis to Program Design, Third Edition 44


Formulas

• Calculate the gross amount:


grossAmount = adultTicketPrice *
noOfAdultTicketsSold
+ childTicketPrice
* noOfChildTicketsSold;
• Calculate the amount donated to the charity:
amountDonated = grossAmount *
percentDonation / 100;
• Calculate the net sale amount:
netSale = grossAmount – amountDonated;

C++ Programming: From Problem Analysis to Program Design, Third Edition 45


Variables

string movieName;
double adultTicketPrice;
double childTicketPrice;
int noOfAdultTicketsSold;
int noOfChildTicketsSold;
double percentDonation;
double grossAmount;
double amountDonated;
double netSaleAmount;
C++ Programming: From Problem Analysis to Program Design, Third Edition 46
Formatting Output
• First column is left-justified
• Numbers in second column are right-justified
• When printing a value in the first column, use
left
• Before printing a value in the second column,
use right
• Use setfill to fill the empty space between
the first and second columns with dots

C++ Programming: From Problem Analysis to Program Design, Third Edition 47


Formatting Output (continued)

• In the lines showing gross amount, amount


donated, and net sale amount

− Use blanks to fill space between the $ sign


and the number

• Before printing the dollar sign

− Use setfill to set the filling character to


blank

C++ Programming: From Problem Analysis to Program Design, Third Edition 48


Main Algorithm
1. Declare variables
2. Set the output of the floating-point to
− Two decimal places
− Fixed
− Decimal point and trailing zeros
3. Prompt the user to enter a movie name
4. Input movie name using getline because
it might contain spaces

C++ Programming: From Problem Analysis to Program Design, Third Edition 49


Main Algorithm (continued)

5. Prompt user for price of an adult ticket

6. Input price of an adult ticket

7. Prompt user for price of a child ticket

8. Input price of a child ticket

9. Prompt user for the number of adult tickets


sold

C++ Programming: From Problem Analysis to Program Design, Third Edition 50


Main Algorithm (continued)
10. Input number of adult tickets sold

11. Prompt user for the number of child tickets


sold

12. Input the number of child tickets sold

13. Prompt user for percentage of the gross


amount donated

14. Input percentage of the gross amount donated

C++ Programming: From Problem Analysis to Program Design, Third Edition 51


Main Algorithm (continued)

15. Calculate the gross amount

16. Calculate the amount donated

17. Calculate the net sale amount

18. Output the results

C++ Programming: From Problem Analysis to Program Design, Third Edition 52


Summary

• Stream: infinite sequence of characters from a


source to a destination
• Input stream: from a source to a computer
• Output stream: from a computer to a destination
• cin: common input
• cout: common output
• To use cin and cout, include iostream header

C++ Programming: From Problem Analysis to Program Design, Third Edition 53


Summary (continued)

• get reads data character-by-character


• putback puts last character retrieved by get
back to the input stream
• ignore skips data in a line
• peek returns next character from input
stream, but does not remove it
• Attempting to read invalid data into a variable
causes the input stream to enter the fail state

C++ Programming: From Problem Analysis to Program Design, Third Edition 54


Summary (continued)

• The manipulators setprecision, fixed,


showpoint, setw, setfill, left, and
right for formatting output
• Include iomanip for the manipulators
setprecision, setw, and setfill

C++ Programming: From Problem Analysis to Program Design, Third Edition 55

You might also like