1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by...

60
1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White

Transcript of 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by...

Page 1: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

1

ACS 168Structured Programming Using

the Computer

Joaquin Vila

Chapter 5

Spring 2002

Prepared

by

Shirley White

Page 2: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

2

Chapter 5I/O Streams as an Introduction to Objects and Classes

In this chapter, we will examine I/O Streams and Basic File I/OTools for Stream I/OCharacter I/OInheritance

Page 3: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

3

I/O Streams as an Introduction to Objects and Classes

I/O refers to Input and Output. Input refers to data flowing INTO your program. Output refers to data flowing OUT OF your

program. Input can be taken from the keyboard or a file. Output can be sent to the screen or to a file Input is transferred to a C++ program from either

a file or the keyboard by means of an input stream.

Output is transferred from a C++ program to the screen or to a file by means of a output stream.

Streams are objects defined in the Standard Library’s header files <iostream> and <fstream>.

Page 4: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

5.1 Streams and Basic File I/O

A stream is a flow of characters (or other kind of data).

Data flowing INTO your program is an input stream. Data flowing OUT OF your program is an output

stream. We have dealt with two of the three standard

streams already: cin and cout. If in_stream and out_stream are input and output

streams, we could write:

int the_number;in_stream >> the_number;out_stream << “the_number is “ << the_number << endl;

4

Page 5: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Why Use Files for I/O?

In a word, files are permanent storage.

Your program is temporary. It runs and is gone, along with any input typed in, and any output generated.

“Permanent storage” is not forever.

5

Page 6: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

File I/O (1 of 5) When a program takes data from a file, we

say the program is reading from the file. When a program sends output to a file, we

say the program is writing to the file. In C++ a stream is a special kind of variable

known as an object. (Objects later.) cin and cout are objects predefined in the

iostream library. File streams, like other variables, must be

declared by the programmer as needed.6

Page 7: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

File I/O (2 of 5)

The #include goes in the normal position at the top of the file.

Example:

#include <fstream>. . .ifstream in_stream;

ofstream out_stream;

These variables are not yet attached to a file, so are not usable.

The fstream library provides a member function named open that ties the stream to a file the outside world knows about. (More later on members of an object.)

Example:

in_stream.open (“infile.dat”); // infile.dat must exist out_stream.open (“outfile.dat”); // outfile.dat will be created.7

Two new code lines need to be embedded in the block of a function.

Two new code lines need to be embedded in the block of a function.

Page 8: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

File I/O (3 of 5)WORDS OF WARNING: In the example:

in_stream.open (“infile.dat”); // infile.dat must exist on your system out_stream.open (“outfile.dat”); // outfile.dat will be created Depending on your system, you may be limited in regard to file name

length. Many systems require at most 8 characters for the name and 3 characters for the extension. More recent systems allow long file names. Read your manuals and ask a local expert.

The file name arguments for open is known as the external name for the file. This name must be a legitimate file name on the system you are using. The stream name is the name of the file in your program.

If you have a file named outfile.dat on your system, and open a file named the same, outfile.dat. in a program, the program will delete the old outfile.dat and replace it with data from your program.

8

Page 9: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

File I/O (4 of 5)

Once we have declared the file variables, in_stream and out_stream, and connected them to files on our system, we can then take input from in_stream and send output to out_stream in exactly the same manner as we have for cin and cout.

Examples:#include <fstream>. . .// appropriate declarations and open statementsint one_number, another_number;in_stream >> one_number >> another_number;

. . .out_stream << “one_number: “ << one_number << “another_number: << another_number;

9

Page 10: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

File I/O (5 of 5) Every file should be closed when your program is through

fetching input or sending output to the file. This is done with the close() function.

Example:in_stream.close():out_stream.close();

Note that the close function takes no arguments. If your program terminates normally, the system will close the

arguments. If the program does not terminate normally, this might not

happen. File corruption is a real possibility. If you want to save output in a file and read it later, the you

must close the file before opening it the second time for reading. 10

Page 11: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

11

A File Has Two Names

Every input and every output file in a program has two names.

The external file name is the real name of the file, which is the name known to the system. It is only used in your program in the call to the open function.

The stream name is the name declared in the program, and that is tied to the external file name with the open statement.

After the call to open, the program always uses the stream name to access the file.

Page 12: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Introduction to Classes and Objects

Consider the code fragment:

#include <fstream>. . .ifstream in_stream; ostream out_stream;in_stream.open (“infile.dat”); out_stream.open (“outfile.dat”);

. . .in_stream.close():out_stream. close();

Here the streams in_stream and out_stream are objects. An object is a variable that has functions as well as data

associated with it. The functions open and close are associated with in_stream

and out_stream, as well as the stream data and file data.12

Page 13: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Introduction to Classes and Objects (cont)

Consider the code fragment:

#include <fstream>. . .ifstream in_stream;

ostream out_stream;

in_stream.open (“infile.dat”); out_stream.open (“outfile.dat”);

. . .

in_stream.close();

out_stream. close(); The functions and data associated with an object are refered to as

members of the object. Functions associated with the object are called member functions. Data associated with the object are called data members. Note that data members are not (usually) accessible to functions

that aren’t members. (More on this later.)13

Page 14: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Summary of Classes and Objects An object is a variable that has functions associated with it. Functions associated with an object are called member functions. A class is a type whose variables are objects. The object’s class determines which member functions the object

has.

Syntax for calling a member function:

Calling_Object.member_function(Argument_List);

Examples: dot operator in_stream.open(“infile.dat”); out_stream.open(“outfile.dat”); out_stream.precision(2); The meaning of the Member_Function_Name is determined by the

class (type of) the Calling_Object.

14

Page 15: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Programming TipChecking that a file was opened successfully

A very common error is attempting to open a file for reading where the file does not exist. The member function open fails then.

Your program must test for this failure, and in the event of failure, manage the error.

Use the istream member function fail to test for open failure.in_stream.fail();

This function returns a bool value that is true if the stream is in a fail state, and false otherwise.

Example:#include <cstdlib> // for the predefined exit(1); library function

. . .in_stream.open(“infile.dat”);

if(in_stream.fail()){ cout << “Input file opening failed. \n”; exit(1); // Predefined function quits the program. }

15Note, this can be any number, but 1 is usually used to indicate an error occurred.Note, this can be any number, but 1 is usually used to indicate an error occurred.

Page 16: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

16

The exit Statement #include <cstdlib> // exit is defined hereusing namespace std; // to gain access to the namesexit(integer_value); // to exit the program

When the exit statement is executed, the program ends immediately.

By convention, 1 is used as an argument for exit() to signal an error.

By convention, 0 is used to signal a normal successful completion of the program. (Use of other values is implementation defined.)

The exit is defined in the cstdlib library header file, so any use requires

– #include <cstdlib>– and a directive to gain access to the names

Page 17: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

17

Display 5.2 File I/O with Checks on open (1 of 2)

//Reads three numbers from the file// infile.dat, sums them, & writes the // sum to the file outfile.dat. #include <fstream>#include <iostream>#include <cstdlib>int main( ){ using namespace std; ifstream in_stream; ofstream out_stream;

in_stream.open("infile.dat"); if (in_stream.fail( )) { cout << "Input file opening " << " failed.\n"; exit(1); }

out_stream.open("outfile.dat");

if (out_stream.fail( )) { cout << "Output file opening failed.\n"; exit(1);

}

int first, second, third;

in_stream >> first >> second >> third;

out_stream << "The sum of the first 3\n"

<< "numbers in infile.dat\n"

<< "is " << (first + second + third)

<< endl;

in_stream.close( );

out_stream.close( );

return 0;

} //end main

Needed for using filesNeeded for using files

Needed for cin and coutNeeded for cin and cout

Needed for using exit(1)Needed for using exit(1)

Declares file names to be used in the program

Declares file names to be used in the programOpens external file named infile.datOpens external file named infile.dat

Verifies that infile.dat opened successfullyVerifies that infile.dat opened successfully

Opens (or creates) external file named outfile.datOpens (or creates) external file named outfile.dat

Verifies that outfile.dat opened successfullyVerifies that outfile.dat opened successfully

Variable declarationsVariable declarations

Gets three integers from the external file infile.dat

Gets three integers from the external file infile.dat

Prints this statement (inserting the sum of the three integers at the end) into the external file out.dat

Prints this statement (inserting the sum of the three integers at the end) into the external file out.datNotice a line return is added to the end.Notice a line return is added to the end.

Closes the two files being usedCloses the two files being used

The return is required since this in NOT a void function.

The return is required since this in NOT a void function.

Page 18: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Summary of File I/O Statements (1 of 3)

Input in this code comes from a file with the directory name infile.dat and output goes to a file outfile.dat

Put the following include directive in your program file:#include <fstream> // for file i/o#include <iostream> // for screen/keyboard i/o#include <cstdlib> // for exit

Choose a stream name for the input the stream, such as in_stream. Declare it to be a variable of type ifstream:using namespace std;ifstream in_stream;ofstream out_stream; 18

These slides are included for you to review the previous code.These slides are included for you to review the previous code.

Page 19: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Summary of File I/O Statements (2 of 3)

Connect each stream to a file using the open member function with external file name as argument. Always use the member function fail to test if the call succeeded.

in_stream.open(“infile.dat”);if (in_streamin.fail());{ cout<< “Input file opening failed.\n”; exit(1);}out_stream.open(“outfile.dat”);if(out_stream.fail()){ cout << “Output file opening failed\n”; exit(1);}

19

Page 20: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Summary of File I/O Statements (3 of 3)

Use the stream in_stream to get input from the file infile.dat just like you use cin input from the keyboard.

Example: in_stream >> some_variable >> another_variable; Use the stream out_stream to send output to the file

outfile.dat just like you use cout output to the screen.

Example: out_stream << “some_variable = “ << some_variable << endl;

Close the streams using the member function close: in_stream.close(); out_stream.close():

20

Page 21: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

21

5.2 Tools for Stream I/O The layout of your program’s output is called the format of

the output. Facilities are provided in C++ to control output format. Recall this set of commands to provide fixed point output

with two decimal places always printed :

cout .setf(ios::fixed);

cout .setf(ios::showpoint);

cout.precision(2); Replacing cout with an ofstream object allows formatting of

file output:

out_stream .setf(ios::fixed);

out_stream .setf(ios::showpoint);

out_stream.precision(2);

Page 22: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

22

Formatting Output with Stream Functions

Every output stream has a member function named precision. From the point of execution of the precision member function, the stream output will be written with either 2 significant figures total, or 2 places after the decimal, depending on the setting of the flag for fixed.

The call to precision affects only the calling stream object. Different output streams may have different settings.

Page 23: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

23

Formatting Output with Stream Functions

cout .setf(ios::showpoint); The ostream member function setf sets flags in

the stream. A stream flag is a variable that controls how the stream behaves. The output stream has many flags.

The ios::showpoint is a value defined in the class ios.

Sending the value ios::showpoint to the setf

member function causes the the decimal point

always to be displayed.

Page 24: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

24

Formatting Output with Stream Functions

cout .setf(ios::fixed); The value ios::fixed is another value that may be passed

to the setf member function to set a corresponding flag in the ostream.

The effect of setting this flag is fixed point notation. A number in fixed point does not use the power-of-ten

notation of scientific notation. Examples:

10.2423 -5034.6565 0.00011007

In fact, there is ios::scientific to cause that output style. Examples: 1.02423e1 -5.0346565e3 1.1007e-4

Page 25: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

25

Formatting Output with Stream Functions

Another useful value is ios::showpos. This value sets a flat that causes a + sign always to be displayed for positive values.

Examples :

+10.2423 -5034.6565 +0.00011007

+1.2423e+10 -5.0346565e+3 +1.1007e-4

Weasel words: Actually getting this particular output will require setting several flags.

Page 26: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

26

Formatting Flags for setf

Flag value Effect Default ios::fixed floating output not in not set

e-notation. Unsets

scientific flag ios::scientific floating point output, not set

will be e-notation as

needed ios::pos a plus (+) sign prefixes not set

all positive output,

including exponents ios::showpointa decimal point and trailing not set

zeros are printed for floating

point output.

Page 27: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

27

Formatting Flags for setfFlag value Effect Default

ios::right if a width is set and output set

fits within, output is right

justified within the field

This flag is cleared by setting

the right flag.

ios::left if a width is set and output not set

fits within, output is left

justified within the field

This flag is cleared by setting

the right flag.

Page 28: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

28

I/O ManipulatorsAn i/o manipulator is a function that is called in a nonstandard

manner. Manipulators are called by insertion into the output stream as if they were data. The stream calls the the manipulator function, changing the state of the i/o stream.

The manipulator setw, with an argument, and the member function width, with an argument, do the same thing.

Example: The output statementcout << “Start”

<< setw(4) << 10 // Print 10 in a field of width 4<< setw(4) << 20 // Print 20 in a field of width 4<< setw(6) << 30; // Print 30 in a field of width 6

generates the following output (where we have numbered the columns)

Start 10 20 30123456789012345678901

4 sp 4 sp 6 sp

Page 29: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

29

Display 5.5 Formatting Output (1 of 2)

//Illustrates output formatting instructions.//Reads all the numbers in the file rawdata.dat and writes the numbers//to the screen and to the file neat.dat in a neatly formatted way.#include <iostream>#include <fstream>#include<cstdlib>#include <iomanip>using namespace std;

void make_neat(ifstream& messy_file, ofstream& neat_file, int number_after_decimalpoint, int field_width);//Precondition: The streams messy_file and neat_file have been connected//to files using the function open.//Postcondition: The numbers in the file connected to messy_file have been//written to the screen and to the file connected to the stream neat_file. //The numbers are written one per line, in fixed point notation (i.e., not in //e-notation), with number_after_decimalpoint digits after the decimal point; //each number is preceded by a plus or minus sign and each number is in a field of//width field_width. (This function does not close the file.)

Needed to use coutNeeded to use cout

Needed to use filesNeeded to use files

Needed to use exit(1)Needed to use exit(1)

Needed to use setwNeeded to use setw

Function prototypeFunction prototype

Page 30: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

30

Formatting Output (2 of 2)

int main( ){ ifstream fin; ofstream fout;

fin.open("rawdata.dat"); if (fin.fail( )) { cout << "Input file opening failed.\n"; exit(1); } fout.open("neat.dat"); if (fout.fail( )) { cout << "Output file opening failed.\n"; exit(1); } make_neat(fin, fout, 5, 12);

fin.close( ); fout.close( );

cout << "End of program.\n"; return 0;}

//Uses iostream, fstream, and iomanip:void make_neat(ifstream& messy_file, ofstream&

neat_file, int number_after_decimalpoint, int field_width)

{ neat_file.setf(ios::fixed); neat_file.setf(ios::showpoint); neat_file.setf(ios::showpos); neat_file.precision(number_after_decimalpoint); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.setf(ios::showpos); cout.precision(number_after_decimalpoint);

double next; while (messy_file >> next) { cout << setw(field_width) << next << endl; neat_file << setw(field_width) << next << endl; }}

Internal variables for file namesInternal variables for file names

Open and verify input fileOpen and verify input file

Open and verify output fileOpen and verify output file

Function callFunction call

Close 2 filesClose 2 files

Function receives input file, output file, requested number of decimal places, and field width

Function receives input file, output file, requested number of decimal places, and field width

Formats output to outfileFormats output to outfile

Formats output to screenFormats output to screen

While loop continues as until it reaches the end of the input file

While loop continues as until it reaches the end of the input file

Takes value from input file and writes it to the output file in requested format

Takes value from input file and writes it to the output file in requested format

Takes value from input file and writes it to the screen in requested format

Takes value from input file and writes it to the screen in requested format

Page 31: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

5.3 Character I/O

Member Functions get and put

C++ provides low level facilities that input and output (raw) character data.

The istream member function get reads one character from the input and stores it in a variable of type char.

char next_symbol;cin.get(next_symbol);

Note that a program can read any character this way: a blank, a newline, or any other character.

31

Page 32: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Member Functions get and putIf the code fragment

char c1, c2, c3, c4, c5 ,c6;cin.get(c1); cin.get(c2);cin.get(c3); cin.get(c4);cin.get(c5); cin.get(c6);

is given input consisting of AB followed by return then CD followed by return:

AB<cr>CD<cr>

then the above code fragment sets c1 to ‘A’, c2 to ‘B’ and c3 to ‘\n’, that is, c3 is set to the newline character, c4 is set to ‘C’, c5 is set to ‘D’ and c6 is set to ‘\n’.

32

Page 33: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Member Functions get and put

Why would we use get? For one thing, your program can detect end-of-line instead

of having the i/o machinery do it for you. This loop will let you read a line of input and stop at the end

of a line. Example code:

cout << “Enter a line of input. I will echo it:\n”;char symbol;do{ cin.get(symbol); cout << symbol;} while (symbol != ‘\n’);

cout << “That all for this demonstration.\n”;

33

Page 34: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Member Function get

Every input stream has a member function get. Syntax:

Input_Stream.get(char_variable);

Example to read a character from the keyboard:char next_symbol;cin.get(next_symbol);

To read from a file, use a file stream instead of cin.

In_stream.get(next_symbol);34

Page 35: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Member Function put

Every input stream has a member function put.Syntax:

output_Stream.put(char_variable);

Example to write to the screen:

cin.put(next_symbol);cin.put(‘a’);

To write to a file, use a file stream instead of cin.

Out_stream.put(next_symbol);

As with all output, you must declare and connect your stream to an output file.

35

Page 36: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

’\n’and “\n” ’\n’ and “\n” seem to be the same thing. They are

NOT the same. Take care to distinguish them. “A cout statement such as

cout << ‘\n’ or cout << “\n”

will produce the same output: flush the output buffer

and write a newline to the output.

HOWEVER: ‘\n’ has type char and “\n” is a cstring literal. “\n” has

type pointer to char, which you will study in ACS169. ‘\n’ and “\n” cannot be compared, nor can either be

assigned to a variable of the other’s type.36

Page 37: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

The putback Member Function (1 of 2)

Sometimes you need to inspect but not remove the next character from the input. You can’t really do this, but you can read the character, decide you didn’t want it, and push it back on the input stream.

The member function, putback, is a member of every input stream. It takes an argument type char, and places the character read from the input (back) there.

37

Page 38: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

The putback Member Function (2 of 2)

Example:fin.get(next);while (next != ‘ ‘){ fout.put(next); fin.get(next);}fin.putback(next);

This code reads characters until a blank is encountered, then puts the blank back on the input.

A final note: The character put back need not have been read! It can be any character. The input file will not be changed, but the program will behave as if it were.

38

This is a priming read that gets the first character.This is a priming read that gets the first character.

The character held in next is put into the outfile.The character held in next is put into the outfile.

The next character in the infile is stored in nextThe next character in the infile is stored in next

The loop repeats until a space has been foundThe loop repeats until a space has been found

The space is “returned” to the input fileThe space is “returned” to the input file

Page 39: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Display 5.6: Checking Input (1 of 2)

If a program does not check input, a single bad character input can ruin the entire run of a program.

This program allows the user to reenter input until input is satisfactory.

Code:

//Program to demonstrate the functions new_line and get_input.#include <iostream>

void new_line( );//Discards all the input remaining on the current input line.//Also discards the ’\n’ at the end of the line.//This version only works for input from the keyboard.

void get_int(int& number);//Postcondition: The variable number has been//given a value that the user approves of. 39

Page 40: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Programming Example: (2 of 2)

int main( ){ using namespace std; int n;

get_int(n); cout << "Final value read in = " << n

<< endl<< "End of demonstration.\n";

return 0;

}//Uses iostream:void new_line( ){ using namespace std; char symbol; do { cin.get(symbol); } while (symbol != '\n');}

40

//Uses iostream:void get_int(int& number){ using namespace std; char ans; do { cout << "Enter input number: "; cin >> number; cout << "You entered " << number << " Is that correct? (yes/no): "; cin >> ans; new_line( ); } while ((ans != 'Y') && (ans != 'y'));}

Function callFunction call

Receives variable n as a call-by-reference parameter and names it number

(notice n has no value at this time)

Receives variable n as a call-by-reference parameter and names it number

(notice n has no value at this time)

Gets value for number from keyboardGets value for number from keyboard

Echoes the enered value for the user to verify

Echoes the enered value for the user to verify

Repeats input until user enters something other than Y or y

Repeats input until user enters something other than Y or y

Function callFunction call

What does this function do???

What does this function do???

The function ends when the user is happy with the value stored in number

The function ends when the user is happy with the value stored in number

Final out put statement is printed on screen and program ends.

Final out put statement is printed on screen and program ends.

An easier way to dump the remaining input buffer is to use

cin.ignore(123, ‘\n’); instead of this function

This can be used for cin or any in_file. The number (123) can actually be any integer, but should be sufficiently large. The ‘\n’ can be any delimiter.

Basically cin.ignore(123, ‘\n’); ignores the next 123 characters or the newline (whichever comes first).

An easier way to dump the remaining input buffer is to use

cin.ignore(123, ‘\n’); instead of this function

This can be used for cin or any in_file. The number (123) can actually be any integer, but should be sufficiently large. The ‘\n’ can be any delimiter.

Basically cin.ignore(123, ‘\n’); ignores the next 123 characters or the newline (whichever comes first).

Page 41: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Pitfall: Unexpected ‘\n’ in Input (1 of 3)

Example with a problem:

cout << “enter a number: \n”;int number;cin >> number;cout <<“enter a letter: \n”;char symbol;cin.get(symbol); With the input

enter a number:21Enter a letter:A

Unfortunately, with this code, the variable number gets 21, but symbol gets a newline, not ‘A’. 41

Page 42: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Pitfall: Unexpected ‘\n’ in Input (2 of 3)

With get, one must account for every character on the input, even the new-line characters.

A common problem is forgetting to account for the newline at the ends of every line.

While it is legal to mix cin >> style input with cin.get() input, the code in the previous slide can cause problems.

You can solve this problem by using the newline() function from the preceding programming example, or the .ignore(int, char) function to dump the characters remaining in the input buffer before using the .get() function. 42

Page 43: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Pitfall: Unexpected ‘\n’ in Input (3 of 3)

Two workable rewrites of the code on prev. slide 1 of 3

cout << “enter a number \n”;int number;cin >> number;cout << “enter a letter: \n”;char symbol;cin >> symbol;

You may write:

cout << “enter a number \n”;int number;cin >> number;new_line();cout << “enter a letter: \n”;char symbol;cin.get(symbol); 43

A third solution would replace this line with

cin.ignore(123, ‘\n’);

A third solution would replace this line with

cin.ignore(123, ‘\n’);

Page 44: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

The eof Member Function(1 of 2)

Every input-file stream has a function to detect end-of-file called eof. The letters stand for end of file.

This function returns a bool value, true if the input file is at end-of-file, false otherwise.

The result of this function can be used to control a while-loop, a for- loop or an if statement.

Typically, what we are really interested in is when we are not at end of file. The code usually reads,

while(! in_stream.eof())

{

// do something with the in_stream

} 44

Page 45: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

The eof Member Function (2 of 2)

The while loop might look like this:

in_stream.get(next);while(! In_stream.eof()){

cout << next; // This could be cout.put(next); in_stream.get(next); // This read is required!

}

This loop reads the file attached to in_stream into the char variable next character by character.

There is an end of file marker that can be read. The eof function does not change from false to true until this marker is read. You can read this marker but writing it out produces unpredictable results.

45

Always use a priming read OUTSIDE the loop!

Page 46: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

46

An Alternate Method for Checking the eof

while(instream >> next) {

cout << next; }

Compared to:

in_stream.get(next);while(! In_stream.eof()){

cout << next; in_stream.get(next);

}

This condition replaces

the priming read AND

the eof check AND

the next read

This condition replaces

the priming read AND

the eof check AND

the next read

Page 47: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

47

Display 5.7Call by Reference parameters (1 of 2)

//Program to create a file called cplusad.dat which is identical to the file//cad.dat, except that all occurrences of ’C’ are replaced by "C++".//Assumes that the uppercase letter ’C’ does not occur in cad.dat, except//as the name of the C programming language.#include <fstream>#include <iostream>#include <cstdlib>using namespace std;

void add_plus_plus(ifstream& in_stream, ofstream& out_stream);//Precondition: in_stream has been connected to an input file with open.//out_stream has been connected to an output file with open.//Postcondition: The contents of the file connected to in_stream have been//copied into the file connected to out_stream, but with each ’C’ replaced//by "C++". (The files are not closed by this function.)

Page 48: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

48

Call by Reference parameters (2 of 2)

int main( ){ ifstream fin; ofstream fout;

cout << "Begin editing files.\n";

fin.open("cad.dat"); if (fin.fail( )) { cout << "Input file opening failed.\n"; exit(1); }

fout.open("cplusad.dat"); if (fout.fail( )) { cout << "Output file opening failed.\n"; exit(1); }

add_plus_plus(fin, fout);

// int main() continued

fin.close( ); fout.close( );

cout << "End of editing files.\n"; return 0;}void add_plus_plus(ifstream&

in_stream, ofstream& out_stream){ char next;

in_stream.get(next); while (! in_stream.eof( )) { if (next == 'C') out_stream << "C++"; else out_stream << next;

in_stream.get(next); }}

Page 49: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Display 5.8: Some predefined character functions(1 of

2)

To access these predefined library functions, your code must contain

#include <cctype>

Here is an abbreviated table of functions from cctype.

Function Description Example .

toupper(char) if char is lowercase char c = toupper(‘a’); transform char to cout << c ; // writes ‘A’

uppercase and return else

return char

tolower(char_expr) lowercase version of toupper

isupper(char_expr) if arg is uppercase char c = ‘a’; return true if (isupper(c)) else return false cout << “Uppercase”;

islower(char_expr) Behavior is as in isupper except islower tests for lowercase

49

Page 50: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Some predefined character functions (2 of 2)

Function Description Example .

isalpha(char) if (‘A’ <= char&& char c = ‘&’; char<= ‘Z’ || if(isalpha(c)) ‘a’ <= char&& cout << c << “ is a letter.”: char<= ‘z’ ) else return true; cout << c << “is not a

letter”.; else

return false;

isdigit(char) if (‘0’ <= char&& char<= ‘0’) if (isdigit(c)) return true; cout << c << “ is a digit.”;

else else return false; cout << c << “ is not a

digit.”;

isspace(char) if (charis any whitespace,

such as tab, newline or blank) return true; else return false; 50

Page 51: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

5.4 Inheritance One of the most powerful features of C++ is the use

of derived classes. A class is derived from another class, means that the

derived class is obtained from the first class by adding features while retaining all the features in the first class.

We speak of the ‘first’ class as the base class. We speak of the derived class inheriting from the

base class, and refer to this mechanism as inheritance.

51

Page 52: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Inheritance Among Stream Classes (1 of 2)

Recall that an object has data and functions. Recall further that a class is a type whose variables

are objects. It turns out that file streams (members of fstream) are

derived from the iostream class. In particular, ifstream inherits from istream, and

ofstream inherits from ostream. Notice that ifstream has the open() member function

but istream does not. Recall that an object has associated data and

functions. A class is a type whose variables are objects.

52

Page 53: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Inheritance Among Stream Classes (2 of 2)

If class D inherits from class B, then B is said to be the base class, and D is said to be the derived class.

If class D inherits from class B, then any object of class D is also an object of class B. Wherever a class B object is used, we can substitute it by a class D object.

If class D inherits from class B, then class B is called the parent class and class D is called the child class.

You will see the words superclass used for base class and subclass used for derived class. Stroustrup, the designer of C++, finds idea that a subclass has more features than the superclass to be counter-intuitive. We weigh in against this usage. These terms are used in several OO languages such as Smalltalk, Java and CLOS. We prefer base class and derived class.

53

Page 54: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Making Stream Parameters Versatile

Suppose you define a function that takes a input stream as an argument and you want the argument to be cin in some cases and an input-file stream in others. To accomplish this, you can use istream as a formal parameter type. Then you can use either an ifstream object or an istream object (cin) as the argument.

Similarly, you can define a function that uses an ostream formal parameter then use either an ofstream object or cout as the argument.

54

Page 55: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Another new_line function

By using an istream formal parameter, we can use this new_line function with either ifstream or istream arguments.

//Uses iostreamvoid new_line(istream & ins){ char symbol; do {

ins.get(symbol); } while (symbol != ‘\n’);}

55

The call could be either

new_line(cin);

or

new_line(in_file);

The call could be either

new_line(cin);

or

new_line(in_file);

Page 56: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Default Arguments (1 of 2)

An alternative to writing two version of new_line() we can write one version with a default argument:

//Uses iostreamvoid new_line(istream & ins = cin){ char symbol; do {

ins.get(symbol); } while (symbol != ‘\n’);}

56

The call could now be:

new_line(); //defaults to cin

or

new_line(in_file);

The call could now be:

new_line(); //defaults to cin

or

new_line(in_file);

Page 57: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Default Arguments (2 of 2)

If a function has several parameters and some of those tend to be consistent, the consistent parameters can be set using default arguments.

However, any parameters assigned default parameters must appear at the end of the parameter list.

In the call, arguments are plugged in for parameters in the order given and any missing arguments are assigned their respective default value.

Consider this function header:void my_func(int num1, double num2 = 5.0, int num3 = 4)

Then the following calls are possible:my_func(num); //assigns num1 the value of num

// and accepts the default values for num2 and num3.

my_func(num, avg); //assigns num1 the value of num, // and num2 the value of avg and accepts the default for num3

Note: It is not possible to send a value for num3 without also sending a value for num2! 57

Page 58: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Summary(1 of 3) A stream of type ifstream can be connected to a file

with the open member function. The program can then take input from the file connected to the stream.

A stream of type ofstream can be connected to a file with the open member function. The program can then send output to the file connected to the stream.

Always use the .fail() member function to check success in opening a file.

A object is a variable that has functions and data associated with it.

A class is a type whose variables are objects. The class determines the associated functions and data.

Syntax for calling a member function of an object:calling_object.member_function_name(Argument_list);

Example: cout.precision(4); 58

Page 59: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Summary(2 of 3) Stream member functions such as width, setf, and

precision, can be used to format output. These member functions work for cout and for ofstream objects.

Stream type formal parameters must be reference parameters.

If the formal parameter is of type istream, the corresponding argument may be either of type istream or ifstream.

Every input stream has a member function named get that reads one character at a time. There is a corresponding member function named put that writes one character to the output stream.

The member function eof can be used to determine whether the the program has reached the end of the input file. (You can also use the alternative method.)59

Page 60: 1 ACS 168 Structured Programming Using the Computer Joaquin Vila Chapter 5 Spring 2002 Prepared by Shirley White.

Summary(3 of 3)

C++ provides for default arguments that provide values for parameters if the corresponding argument in a call are omitted. These arguments must follow any parameters that are not provided default arguments. Calls to such a function must provide arguments for parameters without default arguments first. Arguments beyond this replace default arguments up to the number of parameters the function has.

60