chapter 4 program input and the software design process

50
1 Chapter 4 Program Input and the Software Design Process

Upload: caleb-holmes

Post on 03-Jan-2016

28 views

Category:

Documents


1 download

DESCRIPTION

Chapter 4 Program Input and the Software Design Process. Keyboard. Screen. executing program. No I/O is built into C++. instead, a library provides input stream and output stream. istream. ostream. 2. is header file. for a library that defines 3 objects - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 4 Program Input and the Software Design Process

1

Chapter 4

Program Input and the Software Design Process

Page 2: Chapter 4 Program Input and the Software Design Process

No I/O is built into C++

instead, a library provides input stream and output stream

Keyboard Screenexecutingprogram

istream ostream

2

Page 3: Chapter 4 Program Input and the Software Design Process

<iostream> is header file

for a library that defines 3 objects

an istream object named cin (keyboard)

an ostream object named cout (screen)

an ostream object named cerr (screen)

3

Page 4: Chapter 4 Program Input and the Software Design Process

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;

or by another method, such as

cout << “How old is your dog?”;cin >> ageOfDog;

Page 5: Chapter 4 Program Input and the Software Design Process

>> is a binary operator

>> is called the input or extraction operator

>> is left associative

EXPRESSION HAS VALUE

cin >> age cin

STATEMENT

cin >> age >> weight ;5

Page 6: Chapter 4 Program Input and the Software Design Process

Extraction Operator ( >> )

variable cin is predefined to denote an input stream from the standard input device ( the keyboard )

the extraction operator >> called “get from” takes 2 operands. The left operand is a stream expression, such as cin--the right operand is a variable of simple type.

operator >> attempts to extract the next item from the input stream and store its value in the right operand variable

6

Page 7: Chapter 4 Program Input and the Software Design Process

SYNTAX

These examples yield the same result.

cin >> length ;

cin >> width ;

cin >> length >> width ;

Input Statements

cin >> Variable >> Variable . . . ;

7

Page 8: Chapter 4 Program Input and the Software Design Process

Whitespace Characters Include . . .

blanks tabs end-of-line (newline) characters

The newline character is created by hitting Enter or Return at the keyboard, or by using the manipulator endl or “\n” in a program.

8

Page 9: Chapter 4 Program Input and the Software Design Process

Extraction Operator >>

“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)

9

Page 10: Chapter 4 Program Input and the Software Design Process

char first ; char middle ; char last ;

cin >> first ; cin >> middle ; cin >> last ;

NOTE: Or you could have typed:A[Enter]B[enter]C[enter]If you type: ABC DEF GHI only A,B,C are saved

first middle last

At keyboard you type: A[space]B[space]C[Enter]

first middle last

‘A’ ‘B’ ‘C’

10

Page 11: Chapter 4 Program Input and the Software Design Process

At keyboard you type:[space]25[space]J[space]2[Enter]

int age ; char initial ; float bill ;

cin >> age ; cin >> initial ; cin >> bill ;

NOTE: If illegal input (characters for int or float), the results are unpredictable

age initial bill

age initial bill

25 ‘J’ 2.0

11

Page 12: Chapter 4 Program Input and the Software Design Process

Keyboard and Screen I/O

#include <iostream>

cin

(of type istream)

cout

(of type ostream)

Keyboard Screenexecutingprogram

input data output data

12

Page 13: Chapter 4 Program Input and the Software Design Process

STATEMENTS CONTENTS MARKER POSITION

int i ; 25 A\n char ch ; 16.9\n float x ; cin >> i ; 25 A\n

16.9\n

cin >> ch ; 25 A\n 16.9\n

cin >> x ; 25 A\n 16.9\n

Another example using >>

i ch x

25

25 ‘A’

i ch x

i ch x

i ch x

16.925 ‘A’

NOTE: shows the location of the file reading marker

13

Page 14: Chapter 4 Program Input and the Software Design Process

14

The get( ) function can be used to read a single character.

It obtains the very next character from the input stream without skipping any leading whitespace characters.

Another Way to Read char Data

Page 15: Chapter 4 Program Input and the Software Design Process

char first ; char middle ; char last ;

cin.get ( first ) ; cin.get ( middle ) ; cin.get ( last ) ;

NOTE: The file reading marker is left pointing to the space after the ‘B’ in the input stream.

first middle last

At keyboard you type: A[space]B[space]C[Enter]

first middle last

‘A’ ‘ ’ ‘B’

15

Page 16: Chapter 4 Program Input and the Software Design Process

16

Use function ignore( ) to skip characters

The ignore( ) function is used to skip (read and discard) characters in the input stream. The call

cin.ignore ( howMany, whatChar ) ;

will skip over up to howMany characters or until whatChar has been read, whichever comes first.

Page 17: Chapter 4 Program Input and the Software Design Process

An Example Using cin.ignore( )

a b c

a b c

a b c

a b c

957 34

957 34 128

957 34

NOTE: shows the location of the file reading marker

STATEMENTS CONTENTS MARKER POSITION

int a ; 957 34 1235\n int b ; 128 96\n int c ; cin >> a >> b ; 957 34 1235\n

128 96\n

cin.ignore(100, ‘\n’) ; 957 34 1235\n 128 96\n

cin >> c ; 957 34 1235\n 128 96\n

17

Page 18: Chapter 4 Program Input and the Software Design Process

Another Example Using cin.ignore( )

i ch

957 34

957 34

957 34

i ch

i ch

i ch

16 ‘A’

‘A’

‘A’

NOTE: shows the location of the file reading marker

STATEMENTS CONTENTS MARKER POSITION

int i ; A 22 B 16 C 19\n char ch ;

cin >> ch ; A 22 B 16 C 19\n

cin.ignore(100, ‘B’) ; A 22 B 16 C 19\n

cin >> i ; A 22 B 16 C 19\n18

Page 19: Chapter 4 Program Input and the Software Design Process

19

EXAMPLE

string message ; cin >> message ; cout << message ;

HOWEVER . . .

String Input in C++

Input of a string is possible using the extraction operator >>.

Page 20: Chapter 4 Program Input and the Software Design Process

20

Extraction operator >>

When using the extraction operator ( >> ) to read input characters into a string variable:

the >> operator skips any leading whitespace characters such as blanks and newlines

it then reads successive characters into the string, and stops at the first trailing whitespace character (which is not consumed, but remains waiting in the input stream)

Page 21: Chapter 4 Program Input and the Software Design Process

21

String Input Using >>

string firstName ;

string lastName ;

cin >> firstName >> lastName ;

Suppose input stream looks like this:

Joe Hernandez 23

WHAT ARE THE STRING VALUES?

Page 22: Chapter 4 Program Input and the Software Design Process

22

Results Using >>

string firstName ;

string lastName ;

cin >> firstName >> lastName ;

RESULT

“J o e” “Hernandez”

firstName lastName

Page 23: Chapter 4 Program Input and the Software Design Process

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 ) ;

Page 24: Chapter 4 Program Input and the Software Design Process

24

getline(inFileStream, str)

getline does not skip leading whitespace characters such as blanks and newlines

getline reads successive characters (including blanks) into the string, and stops when it reaches the newline character ‘\n’

the newline is consumed by get, but is not stored into the string variable

Page 25: Chapter 4 Program Input and the Software Design Process

25

String Input Using getline

string firstName ;

string lastName ;

getline (cin, firstName );

getline (cin, lastName );

Suppose input stream looks like this:

Joe Hernandez 23

WHAT ARE THE STRING VALUES?

Page 26: Chapter 4 Program Input and the Software Design Process

26

Results Using getline

“ Joe Hernandez 23” ?

firstName lastName

string firstName ;

string lastName ;

getline (cin, firstName );

getline (cin, lastName );

Page 27: Chapter 4 Program Input and the Software Design Process

Interactive I/O

in an interactive program the user enters information while the program is executing

before the user enters data, a prompt should be provided to explain what type of information should be entered

after the user enters data, the value of the data should be printed out for verification. This is called echo printing

that way, the user will have the opportunity to check for erroneous data

27

Page 28: Chapter 4 Program Input and the Software Design Process

Prompting for Interactive I/O

cout << “Enter part number : “ << endl ; // prompt

cin >> partNumber ;

cout << “Enter quantity ordered : “ << endl ;

cin >> quantity ;

cout << “Enter unit price : “ << endl ;

cin >> unitPrice ;

totalPrice = quantity * unitPrice ; // calculate

cout << “Part # “ << partNumber << endl ; // echo

cout << “Quantity: “ << quantity << endl ;

cout << “Unit Cost: $ “ << setprecision(2)

<< unitPrice << endl ;

cout << “Total Cost: $ “ << totalPrice << endl ; 28

Page 29: Chapter 4 Program Input and the Software Design Process

Disk Files for I/O

your variable

(of type ifstream)

your variable

(of type ofstream)

disk file“C:\myInfile.dat”

disk file“C:\myOut.dat”

executingprogram

input data output data

#include <fstream>

29

Page 30: Chapter 4 Program Input and the Software Design Process

To Use Disk I/O, you must use #include <fstream>

choose valid identifiers (file handles) for your filestreams and declare them

open the files and associate them with disk names

use your filestream identifiers (file handles) in your I/O statements (using >> and << , manipulators, get, ignore)

close the files30

Page 31: Chapter 4 Program Input and the Software Design Process

31

File Names

Complete file names are composed of: A drive letter followed by a colon A path specification of directories

(also called folders by windows) separated by backslashes (\)

Then the file name

Page 32: Chapter 4 Program Input and the Software Design Process

32

File Name Examples

File prog1.cpp in the prog1 directory in the CS115 directory on the C drive:

C:\CS115\prog1\prog1.cpp

Page 33: Chapter 4 Program Input and the Software Design Process

33

Files for your project

You do not have to use complete file names

To open a file on your project directory just use its name: myfile.txt

You only have to use complete file names for files not in your project directory (for example, a flashdrive)

Page 34: Chapter 4 Program Input and the Software Design Process

34

Statements for File I/O

Include fstream library Open the file for reading or writing:

Use file name Associate with file handle

Read/write the file using file handle Close the file

Page 35: Chapter 4 Program Input and the Software Design Process

Statements for Using Disk I/O

#include <fstream> // For file I/O

ifstream inFile; // File handle for reading

ofstream outFile; // File handle for writinginFile.open(“walk.txt”); // open file (read)outFile.open(“results.txt”);//open file (write)inFile >> variables; // Read into variablesoutFile << variables; // Write from variables

infile.close( ); // close files

outfile.close( );

35

Page 36: Chapter 4 Program Input and the Software Design Process

36

Opening a File

• On your project directory:inFile.open(“walk.txt”);

• On the flash drive:inFile.open(“F:\\walk.txt”);

(assuming that F is the drive letter)

• In the temp directory on the C drive:

inFile.open(“C:\\temp\\walk.txt”);

Page 37: Chapter 4 Program Input and the Software Design Process

37

Why \\ and not \ in File Names

In character strings the backslash has a special meaning and is called the escape character

Use of the escape character means “The next character has a special meaning”

Page 38: Chapter 4 Program Input and the Software Design Process

38

Use of the Escape Character

To insert a tab character:

cout <<“\tThis is indented text”<<endl; To end a line (go to next line):

cout<<“Start new line\n”; Use of \n is the same as endl To use a backslash as a character:

cout <<“Backslash:\\”;

Page 39: Chapter 4 Program Input and the Software Design Process

What does opening a file do?

associates the C++ identifier (file handle) 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

39

Page 40: Chapter 4 Program Input and the Software Design Process

40

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.

Page 41: Chapter 4 Program Input and the Software Design Process

41

// *************************************************** // 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.// ***************************************************

#include <iostream> // for cout, endl#include <iomanip> // for setprecision#include <fstream> // for file I/O

using namespace std;

float RoundToNearestTenth( float ); // declare function

Using File I/O

Page 42: Chapter 4 Program Input and the Software Design Process

42

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) float totMiles; // Total of rounded miles float miles; // One rounded mileage ifstream inFile; // Input file identifier ofstream outFile; // Output file identifier

inFile.open(“walk.txt”); // on project directory // inFile.open(“F:\\walk.txt”); // on flashdrive// inFile.open(“C:\\temp\\walk.txt”); // in temp dir. on C

outFile.open(“results.txt”);

Page 43: Chapter 4 Program Input and the Software Design Process

43

// Get data from file

inFile >> distance1 >> distance2 >> distance3 >> distance4 >> scale;

totMiles = 0.0; // Initialize total miles

// Compute miles for each distance on map

miles = RoundToNearestTenth( distance1 * scale );

outFile << distance1 << “ inches on map is “ << miles << “ miles in city.” << endl;

totMiles = totMiles + miles;

Page 44: Chapter 4 Program Input and the Software Design Process

44

miles = RoundToNearestTenth( distance2 * scale );

outFile << distance2 << “ inches on map is “ << miles << “ miles in city.” << endl;

totMiles = totMiles + miles;

miles = RoundToNearestTenth( distance3 * scale );

outFile << distance3 << “ inches on map is “ << miles << “ miles in city.” << endl;

totMiles = totMiles + miles;

miles = RoundToNearestTenth( distance4 * scale );

outFile << distance4 << “ inches on map is “ << miles << “ miles in city.” << endl;

totMiles = totMiles + miles;

Page 45: Chapter 4 Program Input and the Software Design Process

45

// Write total miles to output file

outFile << endl << “Total walking mileage is “ << totMiles << “ miles.” << endl;

return 0 ; // Successful completion}

// ***************************************************

float RoundToNearestTenth ( /* in */ float floatValue)

// Function returns floatValue rounded to nearest tenth.

{ return float(int(floatValue * 10.0 + 0.5)) / 10.0;}

Page 46: Chapter 4 Program Input and the Software Design Process

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

possible reasons for entering fail state include: • invalid input data (often the wrong type) • opening an input file that doesn’t exist • opening an output file on a flashdrive that is

already full46

Page 47: Chapter 4 Program Input and the Software Design Process

Entering File Name at Run Time

#include <string> // contains conversion function c_str

ifstream inFile;

string fileName;

cout << “Enter input file name : “ << endl ; // prompt

cin >> fileName ;

// convert string fileName to a C string type

inFile.open( fileName.c_str( ) );

47

Page 48: Chapter 4 Program Input and the Software Design Process

48

C Strings

C strings are the original (harder to use) way of using character strings

They have been replaced by strings (much easier to use)

However there are built-in functions (such as open) that require C strings

Remember that the parameter types you pass to a function must match what it expects

Page 49: Chapter 4 Program Input and the Software Design Process

49

C Strings

C strings are used in other CS For now use strings For the built-in functions that require

C strings convert them by:stringVariableName.c_str()This returns the C string equivalent of the string variable

Page 50: Chapter 4 Program Input and the Software Design Process

50

The String Class

Strings are really a class You create objects of the class:

string filename; You perform operations (call functions) on

the object:filename.c_str()

The format is:object_name.function

More in other CS courses