Professional Documents
Culture Documents
Chapter 04
Chapter 04
Dale/Weems/Headington
1
Chapter 4 Topics
Input Statements to Read Values for a Program
using >>, and functions get, ignore, getline
Prompting for Interactive Input/Output
Using Data Files for Input and Output
Object-Oriented Design Principles
Functional Decomposition Methodology
2
No I/O is built into C++
3
<iostream> is header file
4
Giving a Value to a Variable
In your program you can assign (give) a value to the
variable by using the assignment operator =
ageOfDog = 12;
5
>> is a binary operator
STATEMENT
cin >> age >> weight ;
6
Extraction Operator ( >> )
variable cin is predefined to denote an input stream
from the standard input device ( the keyboard )
7
Input Statements
SYNTAX
8
Whitespace Characters Include . . .
blanks
tabs
end-of-line (newline) characters
“skips over”
(actually reads but does not store
anywhere)
leading white space characters
as it reads your data from the input
stream (either keyboard or disk file)
10
At keyboard you type:
A[space]B[space]C[Enter]
char first ;
char middle ;
char last ; first middle last
#include <iostream>
executing
Keyboard program Screen
cin cout
15
At keyboard you type:
A[space]B[space]C[Enter]
char first ;
char middle ;
char last ; first middle last
17
An Example Using cin.ignore( )
NOTE: shows the location of the file reading marker
EXAMPLE
string message ;
cin >> message ;
cout << message ;
HOWEVER . . .
20
Extraction operator >>
When using the extraction operator ( >> ) to
read input characters into a string variable:
Joe Hernandez 23
RESULT
“J o e” “Hernandez”
firstName lastName
23
getline( ) Function
Because the extraction operator stops reading at
the first trailing whitespace, >> cannot be used
to input a string with blanks in it
use getline function with 2 arguments to
overcome this obstacle
First argument is an input stream variable, and
second argument is a string variable
EXAMPLE
string message ;
getline (cin, message ) ;
24
getline(inFileStream, str)
getline does not skip leading whitespace
characters such as blanks and newlines
25
String Input Using getline
string firstName ;
string lastName ;
getline (cin, firstName );
getline (cin, lastName );
Joe Hernandez 23
firstName lastName
27
Interactive I/O
in an interactive program the user enters
information while the program is executing
#include <fstream>
input data output data
32
What does opening a file do?
associates the C++ identifier for your file with
the physical (disk) name for the file
if the input file does not exist on disk, open is
not successful
if the output file does not exist on disk, a new
file with that name is created
if the output file already exists, it is erased
places a file reading marker at the very
beginning of the file, pointing to the first
character in it 33
Map Measurement Case Study
You want a program to determine
walking distances between 4 sights in the
city. Your city map legend says one inch
on the map equals 1/4 mile in the city.
Read from a file the 4 measured
distances between sights on the map and
the map scale.
Output to a file the rounded (to the
nearest tenth) walking distances between
the 4 sights. 34
Using File I/O
// ***************************************************
// Walk program using file I/O
// This program computes the mileage (rounded to nearest
// tenth of mile) for each of 4 distances, using input
// map measurements and map scale.
// ***************************************************
35
int main( )
{
float distance1; // First map distance
float distance2; // Second map distance
float distance3; // Third map distance
float distance4; // Fourth map distance
float scale; // Map scale (miles/inch)
36
// Get data from file
37
miles = RoundToNearestTenth( distance2 * scale );
38
// Write total miles to output file
// ***************************************************
{
return float(int(floatValue * 10.0 + 0.5)) / 10.0;
}
39
Stream Fail State
when a stream enters the fail state, further I/O
operations using that stream have no effect at
all. But the computer does not automatically
halt the program or give any error message
ifstream inFile;
string fileName;
inFile.open( fileName.c_str( ) );
41
Functional Decomposition
A technique for developing a program in which the
problem is divided into more easily handled
subproblems, the solutions of which create a
solution to the overall problem.
Round To
Nearest Tenth
44
Object-Oriented Design
A technique for developing a program in which
the solution is expressed in terms of objects --
self- contained entities composed of data and
operations on that data.
cin cout
>> <<
ignore setw
45
More about OOD
languages supporting OOD include: C++, Java,
Smalltalk, Eiffel, CLOS, and Object-Pascal
FUNCTION OBJECT
Operations
FUNCTION Data
OBJECT
OBJECT Operations
FUNCTION
Operations Data
Data
48
What is an object?
OBJECT
set of functions
Operations
49
An object contains data and operations
checkingAccount
OpenAccount
Private data:
WriteCheck
accoutNumber
MakeDeposit
balance
IsOverdrawn
GetBalance
50
Why use OOD with large
software projects?
objects within a program often model real-life
objects in the problem to be solved
52
Algorithm for Company
Payroll Program
Initialize total company payroll to 0.0
Repeat this process for each employee
1. Get the employee’s ID empNum
2. Get the employee’s hourly payRate
3. Get the hours worked this week
4. Calculate this week’s wages
5. Add wages to total company payroll
6. Write empNum, payRate, hours, wages to file
Write total company payroll on screen. 53
Company Payroll Program
// ***************************************************
// Payroll program
// This program computes each employee’s wages and
// the total company payroll
// ***************************************************
54
C++ Code Continued
int main( )
{
float payRate; // Employee’s pay rate
float hours; // Hours worked
float wages; // Wages earned
float total; // Total company payroll
int empNum; // Employee ID number
ofstream payFile; // Company payroll file
55
cout << “Enter employee number: “; // Prompt
cin >> empNum; // Read ID number
56
cout << “Total payroll is “
<< total << endl;
// ***************************************************
{
if ( hours > MAX_HOURS )
wages = (MAX_HOURS * payRate ) +
(hours - MAX_HOURS) * payRate * OVER_TIME;
else
wages = hours * payRate;
} 57 57