38
Streams, Files, and Formatting Chapter 8

Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

Embed Size (px)

Citation preview

Page 1: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

Streams, Files, and Formatting

Chapter 8

Page 2: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

2

8.1 Standard Input/Output Streams

Stream is a sequence of characters Working with cin and cout Streams convert internal representations to

character streams >> input operator (extractor) << output operator (inserter) Streams have no fixed size

Page 3: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

3

Reading Data >>

Leading white space skipped <nwln> also skipped Until first character is located

cin >> ch; Also read character plus white space as a

character– get and put functions

Page 4: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

4

CountChars.cpp

// File: CountChars.cpp

// Counts the number of characters and lines in

// a file

#include <iostream>

#include <string>

using namespace std;

#define ENDFILE "CTRL-Z"

Page 5: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

5

CountChars.cpp

int main()

{

const char NWLN = '\n'; // newline character

char next;

int charCount;

int totalChars;

int lineCount;

lineCount = 0;

totalChars = 0;

Page 6: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

6

CountChars.cpp

cout << "Enter a line or press " << ENDFILE <<

": ";

while (cin.get(next))

{

charCount = 0;

while (next != NWLN && !cin.eof())

{

cout.put(next);

charCount++;

totalChars++;

cin.get(next);

} // end inner while

Page 7: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

7

CountChars.cpp

cout.put(NWLN);

lineCount++;

cout << "Number of characters in line " <<

lineCount << " is " << charCount << endl;

cout << "Enter a line or press " <<

ENDFILE << ": ";

} // end outer while

cout << endl << endl <<

"Number of lines processed is " <<

lineCount << endl;

Page 8: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

8

CountChars.cpp

cout << "Total number of characters is " <<

totalChars << endl;

return 0;

}

Page 9: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

9

8.2 External Files

Batch– Requires use of data files (save to disk)– Batch can be run during off peak use– allows things to be complete at start of day

Interactive– Real time systems– Ok for smaller programs– Programs that complete quickly

Page 10: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

10

Files

Naming– .cpp .dat .out .in

How to attach files to the stream– stream object– external file name– internal name– open

Additional functions as part of fstream.h class

Page 11: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

11

Files

Declare the stream to be processed need to #include fstreamifstreamins; // input stream

ofstream outs; // output stream Need to open the files

ins.open (inFile);

outs.open (outFile);

Page 12: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

12

Files

#define associates the name of the stream with the actual file name

fail() function - returns true if file fails to open

Program CopyFile.cpp demonstrates the use of the other fstream functions– get , put, close and eof– discuss program

Page 13: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

13

CopyFile.cpp

// File: CopyFile.cpp

// Copies file InData.txt to file OutData.txt

#include <cstdlib>

#include <fstream>

using namespace std;

// Associate stream objects with external file

// names

#define inFile "InData.txt"

#define outFile "OutData.txt"

Page 14: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

14

CopyFile.cpp

// Functions used ...

// Copies one line of text

int copyLine(ifstream&, ofstream&);

int main()

{

// Local data ...

int lineCount;

ifstream ins;

ofstream outs;

Page 15: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

15

CopyFile.cpp

// Open input and output file, exit on any

// error.

ins.open(inFile);

if (ins.fail ())

{

cerr << "*** ERROR: Cannot open " <<

inFile << " for input." << endl;

return EXIT_FAILURE;// failure return

} // end if

Page 16: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

16

CopyFile.cpp

outs.open(outFile);

if (outs.fail())

{

cerr << "*** ERROR: Cannot open " <<

outFile << " for output." << endl;

return EXIT_FAILURE;// failure return

} // end if

// Copy each character from inData to outData.

lineCount = 0;

do

{

Page 17: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

17

CopyFile.cpp

if (copyLine(ins, outs) != 0)

lineCount++;

} while (!ins.eof());

// Display a message on the screen.

cout << "Input file copied to output file." <<

endl;

cout << lineCount << " lines copied." << endl;

ins.close();

outs.close();

return 0; // successful return

}

Page 18: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

18

CopyFile.cpp

// Copy one line of text from one file to another

// Pre: ins is opened for input and outs for

// output.

// Post: Next line of ins is written to outs.

// The last character processed from

// ins is <nwln>;

// the last character written to outs

// is <nwln>.

// Returns: The number of characters copied.

int copyLine (ifstream& ins, ofstream& outs)

{

Page 19: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

19

CopyFile.cpp

// Local data ...

const char NWLN = '\n';

char nextCh;

int charCount = 0;

// Copy all data characters from stream ins to

// stream outs.

ins.get(nextCh);

while ((nextCh != NWLN) && !ins.eof())

{

outs.put(nextCh);

charCount++;

Page 20: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

20

CopyFile.cpp

ins.get (nextCh);

} // end while

// If last character read was NWLN write it

// to outs.

if (!ins.eof())

{

outs.put(NWLN);

charCount++;

}

return charCount;

} // end copyLine

Page 21: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

21

CopyFile.cpp

Program Output

Input file copied to output file.

37 lines copied.

Page 22: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

22

File Processing

Loop processing– for loops– while loops

Newline character– eof() function returns a False if file is not empty

while ( ! ins.eof())

{

do stuff

}

Page 23: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

23

8.3 Using External File Functions

Payroll Case Study Two programs process the payroll Design Process

– Problem Analysis– Program Design– Program Implementation– Program Verification and Test

Page 24: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

24

Payroll Case Structure Chart

P re pa refi les

P roce ss a lle m p lo yees

D isp layp ay ro ll

W r i te thep ayro ll f i le

processEmp

Page 25: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

25

ProcessEmp Structure Chart

R e ad e m p loyeefirs t a n d la st

n a m es

R e ad e m p loyeesa la ry d a ta (h ou rs

a n d ra te )

C o m p u tesa la ry

A ddsa la ry to

to ta l p ay ro ll

W r i te f i r sta n d la st n am es

a nd sa la ry

P roce ss a lle m p lo yees

Page 26: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

26

Payroll.cpp

// File: Payroll.cpp

// Creates a company employee payroll file

// computes total company payroll amount

#include <fstream>

#include <cstdlib>

#include "money.h"

#include "money.cpp"

using namespace std;

Page 27: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

27

Payroll.cpp

// Associate streams with external file names

#define inFile "EmpFile.txt" // employee file

#define outFile "Salary.txt" // payroll file

// Functions used ...

// PROCESS ALL EMPLOYEES AND COMPUTE TOTAL

money processEmp(istream&, ostream&);

int main()

{

ifstream eds;

ofstream pds;

money totalPayroll;

Page 28: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

28

Payroll.cpp

// Prepare files.

eds.open(inFile);

if (eds.fail ())

{

cerr << "*** ERROR: Cannot open " << inFile

<< " for input." << endl;

return EXIT_FAILURE;// failure return

}

pds.open(outFile);

if (pds.fail())

{

Page 29: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

29

Payroll.cpp

cerr << "***ERROR: Cannot open " << outFile << " for output." << endl; eds.close(); return EXIT_FAILURE; // failure return }

// Process all employees and compute total // payroll. totalPayroll = processEmp(eds, pds);

// Display result. cout << "Total payroll is " << totalPayroll <<

endl;

Page 30: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

30

Payroll.cpp

// Close files.

eds.close();

pds.close();

return 0;

}

Page 31: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

31

Payroll.cpp

// Insert processEmp here.

// Process all employees and compute total

// payroll amount

// Pre: eds and pds are prepared for

// input/output.

// Post: Employee names and salaries are

// written from eds to pds

// and the sum of their salaries is returned.

// Returns: Total company payroll

money processEmp (istream& eds, ostream& pds)

{

Page 32: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

32

Payroll.cpp

string firstName;

string lastName;

float hours; // input: hoursWorked

money rate; // input: hourly rate

money salary; // output: gross salary

money payroll; // return value - total company payroll

payroll = 0.0;

// Read first employee's data record.

eds >> firstName >> lastName >> hours >> rate;

Page 33: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

33

Payroll.cpp

while (!eds.eof())

{

salary = hours * rate;

pds << firstName << lastName << salary <<

endl;

payroll += salary;

// Read next employee's data record.

eds >> firstName >> lastName >> hours >>

rate;

} // end while

return payroll;

} // end processEmp

Page 34: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

34

PayrollFile.cpp

Program Output

Total payroll is $677.38

Page 35: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

35

8.4 More on Reading String Data

Getline - could be used to process an entire line of data

Use # as a delimiter charactergetline (eds, name, ‘#’);

Advance the newlinegetline (eds, name, ‘\n’);

Use care when choosing cin, get or getline

Page 36: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

36

8.5 Input/Output Manipulators

Chapter 5 covered setf, unsetf, precision and width

Can be used with the cout and << Table 8.3 lists various manipulator functions

(setiosflags, setprecision, setw) #include iomanip when using Can be used with external files like stdout

and stdin

Page 37: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

37

Formatting with State Flags

Depending on the setiosflags or unsetiosflags– Output can be controlled by other format state

flag– Flags are enumerated types

ios::flagname Table 8.3 lists some flags

– boolalpha, fixed, left, right, showpoint etc

Page 38: Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams

38

8.6 Common Programming Errors

Connecting streams and external files– Declare stream object and open the file

Watch use of while loops when processing– Test values see what you actually have

Reading past the eof White space Newline character Formatting via flags