Chapter 3

advertisement
C++ Programming: Program Design Including Data Structures, Fourth Edition
Chapter 3
Input/Output
At a Glance
Instructor’s Manual Table of Contents

Overview

Objectives

Teaching Tips

Quick Quizzes

Class Discussion Topics

Additional Projects

Additional Resources

Key Terms
3-1
C++ Programming: Program Design Including Data Structures, Fourth Edition
3-2
Lecture Notes
Overview
Chapter 3 explores I/O operations in more detail. Students will learn how I/O statements
extract input from the standard input device and send output to the standard output
device. They will become more familiar with using predefined functions and learn
about several manipulators that are used to format output. Finally, students will enhance
their knowledge of I/O by extending the operations associated with standard
input/output devices to files.
Objectives
In this chapter, the student 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, putback, and peek
 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
Teaching Tips
I/O Streams and Standard I/O Devices
1. Review the three major operations a program performs: get data, manipulate data, and
output the results.
2. Mention that C++ provides an extensive I/O library of predefined functions.
3. Introduce the concept of an I/O stream as a sequence of bytes from a source to a
destination. Define the terms input and output stream, and the terms common input and
common output.
Teaching
Tip
You might set aside some extra time to discuss streams, as they may be a new
concept for some students. Draw an analogy to how traffic travels across a
network as a sequence of bytes.
C++ Programming: Program Design Including Data Structures, Fourth Edition
3-3
4. Discuss the C++ data types istream and ostream and describe their role in I/O
operations.
cin and the Extraction Operator >>
1. Explain how the extraction operator works. Point out that it is a binary operator in
which the left-side operand is an input stream variable and the right-side operand is a
variable of a simple data type.
2. Review the syntax of an input statement and note that the extraction operator can be
used several times in one statement.
3. Define whitespace characters and point out that the extraction operator skips over
whitespace when scanning for input.
4. Emphasize that the extraction operator distinguishes ambiguous data types based on the
right-side operand’s data type. Note that input failure will occur if there is a mismatch
between user input and the input variable.
5. Step through Example 3-1 with your students to illustrate various ways to use cin and
the extraction operator.
Teaching
Tip
The extraction operator is probably fascinating to your students because of its
multifaceted functionality. Use this opportunity to briefly introduce the concept
of operator overloading.
Using Predefined Functions in a Program
1. Discuss the role of functions in a C++ program. Explain that the main function in C++
executes automatically when a program is run, but other functions are activated when
called. Define the terms function call and arguments/parameters.
2. Remind students that C++ provides several predefined functions in a collection of
libraries. Explain that these are accessed through the appropriate header files.
3. Describe some of the functions available in the cmath and string header files. Use
Example 3-2 to illustrate how to use these functions in a program.
C++ Programming: Program Design Including Data Structures, Fourth Edition
Teaching
Tip
3-4
The following sections introduce several functions that are useful for I/O
operations. However, the syntax for calling functions may be new for students.
Before beginning this section, briefly explain how to access functions using the
dot operator and how to indicate function arguments in parentheses. You might
want to refer to the material in the last section of this heading, and then review
those concepts again later. This is also a good opportunity to introduce objectoriented concepts by mentioning that istream and ostream are actually
objects with member functions.
cin and the get Functions
1. Describe the functionality of get and discuss situations in which using it is preferable
to cin.
cin and the ignore Function
1. Explain how the ignore function is useful when processing partial data.
2. Discuss the syntax of this function and the details of how and which types of characters
are ignored. Use Examples 3-3 and 3-4 to illustrate.
The putback and peek Functions
1. Describe the purpose and syntax of the putback function.
2. Describe the peek function and why it is useful in processing input. Emphasize the
syntactic differences in accessing this function and illustrate its use with Example 3.5.
The Dot Notation Between I/O Stream Variables and I/O Functions:
A Precaution
1. Review function notation, including dot operators, parameters, and the concept of
member functions. Verify that students have a good understanding of these concepts, as
they will serve as a foundation for introducing objects.
Quick Quiz 1
1. An expression such as pow(2,3) is called a(n) ____________________.
Answer: function call
2. Which header file contains the sqrt function?
Answer: cmath
C++ Programming: Program Design Including Data Structures, Fourth Edition
3-5
3. What is the syntax of the ignore function?
Answer: cin.ignore(intExp, chExp);
4. The get function presented in this chapter only reads values of type
____________________.
Answer: char
Input Failure
1. Explain that input failure occurs when the input data does not match the corresponding
variables. Execute the program in Example 3-6 to demonstrate how the system responds
to input failure.
The clear Function
1. Describe the purpose of the clear function. Use Example 3-7 to demonstrate how the
clear function can be used with the ignore function to restore an input stream from
failure.
Teaching
Tip
Ask your students what would happen if the variable b was not initialized in
Example 3-7. Then illustrate by executing the program without the initialization
statement.
Output and Formatting Output
1. This section describes how to format output, particularly floating-point numbers.
Briefly review the syntax of cout and << before discussing manipulator functions.
setprecision Manipulator
1. Describe how to use setprecision to format the number of decimal places in
floating-point numbers. Note that the iomanip header file must be included to use this
function.
fixed Manipulator
1. Explain the purpose of the fixed and scientific manipulators.
showpoint Manipulator
1. Explain how showpoint can be used with fixed to force the display of decimal
point and trailing zeros when the decimal portion of a decimal is zero.
C++ Programming: Program Design Including Data Structures, Fourth Edition
3-6
2. Use Example 3-8 to illustrate the use of all the manipulators discussed thus far.
setw
1. Explain how setw formats the value of an expression in a specific number of columns
and mention that the formatting is right-justified. Illustrate with Example 3-9.
2. Note that the iomanip header file needs to be included to use this function.
Quick Quiz 2
1. Write a statement to format the output of decimal numbers to two decimal places.
Answer: cout << setprecision(2);
2. To force the output to show the decimal point and trailing zeros of a decimal number,
use the ____________________ manipulator.
Answer: showpoint
3. True or False: The setw manipulator cannot use a string as an argument.
Answer: False
4. The header file ____________________ needs to be included to use the setw function.
Answer: iomanip
Additional Output Formatting Tools
1. This section describes additional formatting tools to give the programmer more control
over output.
setfill Manipulator
1. Explain that setfill is used with setw to fill unused columns with a specified
value. Illustrate with Example 3-10.
left and right Manipulators
1. Mention that the left and right manipulators are used to justify output and illustrate
with Example 3-11.
Input/Output and the string Type
1. Explain that cin can be used to read a string. However, emphasize that getline
should be used instead if you would like to read a string containing blanks. Go over the
syntax of the getline function.
C++ Programming: Program Design Including Data Structures, Fourth Edition
Teaching
Tip
3-7
Discuss specific situations in which using getline is preferable to cin, and
vice versa.
File Input/Output
1. Discuss the situations in which file input/output is preferable to a standard input/output
device.
2. Explain how the fstream header file provides file I/O through the ifstream and
ofstream data types. Emphasize that unlike the cin and cout variables of
iostream, file stream variables must be declared by the programmer.
3. Describe the five-step process of file I/O. Explain how to use ifstream and
ofstream to open and close input and output files. Illustrate the process with the
skeleton program provided in this section.
4. Step through the movie and student grade Programming Examples at the end of the
chapter to consolidate the students’ understanding of the I/O operations presented.
Teaching
Tip
It might be helpful to show students how to create a simple data file and discuss
appropriate file extensions. Test the input data file in class with a short program.
Quick Quiz 3
1. Define a file.
Answer: An area in secondary storage used to hold information
2. True or False: File stream variables are predefined in the fstream header file and
associated with input/output sources.
Answer: False
3. The stream member function ____________________ is used to open files.
Answer: open
4. Write a statement that closes the file stream outData.
Answer: outData.close();
C++ Programming: Program Design Including Data Structures, Fourth Edition
3-8
Class Discussion Topics
1. Why do several functions in iostream and fstream have identical names? When is
it advantageous to reuse function names?
2. Some of the input/output functions employ syntax that is difficult to remember. Ask
students to think of ways to increase efficiency when reusing these or other functions in
a number of programs.
Additional Projects
1. Ask students to write a program that asks the user for their name, favorite movie,
favorite restaurant, and favorite song. The results should output to a file named
favorites.txt. Each execution of the program should append to the file, not overwrite it,
so that the file will include a list of “favorites.”
2. Ask students to write a program that calculates the body mass index of the user. After
outputting the BMI, the program should display possible BMI ranges and their meaning.
These should be extracted directly from an input file that you have created. You can
find more information about BMI here: www.cdc.gov/nccdphp/dnpa/bmi/index.htm.
Additional Resources
1. Formatting your output with C++ streams:
www.informit.com/articles/article.asp?p=170770&rl=1
2. Input/output with files:
www.cplusplus.com/doc/tutorial/files.html
3. Formatting cout output in C++ using iomanip:
www.cprogramming.com/tutorial/iomanip.html
4. Operator overloading in C++:
www.devarticles.com/c/a/Cplusplus/Operator-Overloading-in-C-plus/
Key Terms
 Arguments (parameters): values that are passed in a function call in the parentheses
after the name of the function
 Common input: the variable cin is named after this
 Common output: a variable cout is named after this
 Dot notation: dot separates the input stream variable name from the member, or
function name
C++ Programming: Program Design Including Data Structures, Fourth Edition
3-9
 Fail state: the state an input stream enters after input failure in which all further I/O
statements using that stream are ignored
 File: area in secondary storage used to hold information
 File stream variables: include ifstream variables for input and ofstream
variables for output
 Function call: transfers control from the main function to the first statement in the body
of the function, such as pow(2,3)
 Input failure: happens when the input data does not match the corresponding variables
in the program and the program either fails to compile or yields incorrect results
 Input stream: sequence of characters from an input device to the computer
 Input stream variables: variables of the type istream
 istream member functions: functions that are associated with the data type
istream
 Member access operator: dot operator in C++
 Opening a file: associating a file stream variable with an input/output source
 Output stream: sequence of characters from the computer to an output device
 Output stream variables: variables of the type ostream
 Parameterized stream manipulators: manipulators with parameters
 Predefined functions: functions that are already defined in C++
 Stream: sequence of characters from the source to the destination
 Stream member functions (stream functions): I/O functions such as get
 Stream variables: either an input stream variable or an output stream variable
Download
Study collections