1 simple file i/o chapter 11 switch statement chapter 12

33
1 Simple File I/O Chapter 11 Switch Statement Chapter 12

Upload: sharyl-fleming

Post on 31-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

1

Simple File I/O Chapter 11

Switch StatementChapter 12

Page 2: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

2

Agenda

File names and file streamsIntro to Classes and Objects

End-of-file Loops

Formatting Output

Switch statement

Page 3: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

3

The need for files in programming

Oracle Testing—allows rapid data entry for thorough testing of all branches of code (every if, else, case, etc)

Recording Output—maintaining records of program executions

Word processing—storing documents that can be edited and revised when a word processor runs

Page 4: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

4

File Names and Types

A file name should reflect its contents Payroll.dat

Students.txt

Grades.txt

A file’s extension indicates the kind of data the file holds

.dat, .txt general program input or output

.cpp C++ source file

.doc Microsoft word document

Page 5: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

5

I/O Streams

A stream in C++ is a conduit (pipe) through which data passesInput passes through the istream object and output passes through the ostream object. Input and output are managed by the istream object cin and the ostream object coutThe istream class defines the use of the extraction operator ‘ >> ’ (used with cin)

Page 6: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

6

Stream Extraction and Insertion

#include <iostream>

Input (stream extraction):cin

>> // takes data from stream and sticks in variable

Output (stream insertion):cout

<< // takes data from variable and puts into stream

Input (Extraction) skips whitespace!‘\n’, ‘\t’, ‘ ‘, ‘\r’, ‘\v’

Page 7: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

7

Input and Output File StreamsInput from a file is managed by an ifstream object in the same way that the input from the keyboard is managed by the istream object cinSimilarly, output to a file is managed by an ofstream object in the same way that the output to the monitor is managed by the ostream object coutThe difference is that ifstream and ofstream objects have to be declared explicitly and initialized with the external name of the file which they manage#include the <fstream> header file

Page 8: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

8

Files: Let’s Use Them

#include <fstream>

Declare a file stream variableifstream inFile; //input file stream

ofstream outFile; //output file stream

Open the filesinFile.open(“MyInput.dat”);

outFile.open(“MyOutput.dat”);

Page 9: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

9

#include<fstream>#include<iostream> void main() Create a new file stream newfile { ofstream newfile;

Connect newfile to the file on disk

newfile.open("students.txt");

newfile<<“this is written to the file”;cout<<“this is written to the monitor”;

}

Output File Stream Example

Page 10: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

10

Write a database file, Lab 11 prob 1)

char done = 'y';

int acntnum; //an account number

float balance; // an account balance

ofstream outfile; // a file variable.

outfile.open ("accnts.dat");

// prepare database file for writing

a) Setting up Output File

Page 11: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

11

Lab 11 prob 1) continued// Now input values from keyboard and write to the disk.

while (done != 'n'){ cout << "enter an accnt number and balance: ";

cin >> acntnum >> balance; outfile << acntnum << " " << balance << endl;cout << "another account? enter `y' or `n':";cin >> done;

}}

Download Lab11 & Try 1) Now!

b) Using output file

Page 12: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

12

Lab 11 Prob 2) Now Read database file

float sum = 0.0;ifstream infile; // a file var. for the input

infile.open ("accnts.dat"); //prepare file for reading

for (n=0; n<3; n++) // sum 3 accounts...{ infile >> acntnum >> balance;

sum += balance;}cout << "The total of all accounts is: " << sum ;

Same file we wrote to

Page 13: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

13

Always Close your FilesDon’t forget to close the files when you are done with them

infile.close( );

outfile.close( );

Handles any final writing and lets file be re-opened later in program.

Put this after all reads/writes are finished (usually right before program or function terminates)

Page 14: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

14

Alternative Opening Syntax

Instead of Declaring then opening:ifstream infile;

infile.open(“accts.dat”);

You can Declare and Open in one statementifstream infile(“accts.dat”);

ofstream outFile(“accts.dat”);

Page 15: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

15

Agenda

File names and file streams

Intro to Classes and ObjectsEnd-of-file Loops

Formatting Output

Page 16: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

16

Intro to Objects and ClassesAn object is a variable that has functions and data associated with itinfile and outfile each have a function named open( ) associated with them

infile and outfile use different versions of a function named open

• One version of open is for input files

• A different version of open is for output files

Page 17: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

17

Calling a Member Function

Calling a member function requires first specifying the object containing the function

The calling object is separated from the member function by the dot operator

Example: inFile.open(“accts.dat");

Calling object

Dot operator

Member function

Page 18: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

18

ClassesA type whose variables are objects, is a classifstream is the type of the infile variable (object)

ifstream is a class

The class of an object determines its member functions

Example: ifstream inputFile, inputData;•inputFile.open and inputData.open are the same

function but might be given different filenames to open

Page 19: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

19

Class Member Functions

The member functions an object can use are defined in its class definition

The class determines the member functions of the object

The class ifstream has an open function

Every variable (object) declared of type ifstream has that open function available

Page 20: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

20

Agenda

File names and file streams

Intro to Classes and Objects

End-of-file Loops Formatting Output

Page 21: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

21

Other Capabilities of File Streams

A File stream object maintains a true/false value that can be tested to check an operationifstream infile;

infile.open(“accts.dat”);

if (!infile)

{ cout<<“file not found”;

exit(1);

}

If open was unsuccessful…

This message is displayed

And program quits

Page 22: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

22

Loop until end-of-fileProcess indefinite list in a file:

infile>>acntnum>>balance;while(infile){// process last data

// get next datainfile>>acntnum>>balance;

}

Check stream status

after each read

Page 23: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

23

A more compact versionProcess indefinite list in a file:

while(infile>>acntnum>>balance)

{

// process data

} Read data and Check status after each read

Page 24: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

24

Agenda

File names and file streams

Intro to Classes and Objects

End-of-file Loops

Formatting Output

Page 25: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

25

Tools for Stream FormattingRunning Lab 11 Prob 1, if we enter

111 123.45222 444.77777777733 12000000.22

We get an accnts.dat file that looks like this:111 123.45222 444.77833 1.2e+07

Page 26: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

26

Formatting Output to FilesRemember to #include <iomanip>Use setprecision(2) --

to force 2 digits of precision for all float data

Use fixed – to force fixed point formatting (no e-notation allowed) for all following data

Use left (-- or right)to justify (line up) on left or right side of columnstrings look better with left, numbers with right

Use setw(10) to output data right justified in a field of 10 spacesOnly applies to next data

Page 27: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

27

Lab 11 Prob1) With Formatting

while (done != 'n')

{

cout << "enter an account number and balance: ";

cin >> acntnum >> balance;

outfile<<setprecision(2)<<fixed<< setw(10)

<< acntnum <<setw(15) << balance << endl;

cout << "another account? enter `y' or `n':";

cin >> done;

}

#include <iomanip>

Page 28: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

28

The Result!NOW running Listing 8.1 MODIFIED, if we enter

111 123.45222 444.77777777733 12000000.22

We get an accnts.dat file that looks like this: 111 123.45 222 444.78 33 12000000.00

Page 29: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

Slide 29

Creating Space in Output The setw function specifies the number of

spaces for the next item Applies only to the next item of output

Example: To print the digit 7 in four spaces use outfile<<setw(4)<< 7 << endl; Three of the spaces will be blank

7

(ios::left)

Page 30: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

30

switch Statement

Can be used instead of if-else-ifswitch(expression)

{

case constant1: statementList1;

case constant2: statementList2;

case constantN: statementListN;

default: statementList0;

}

Page 31: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

31

switch in Practice…a menuchar choice;cin>>”enter P for payroll, E for employee info, Q to quit”<<endl;

cin>>choice;switch (choice){case ‘P’: cout<<“processing payroll”; break;

case ‘E’: case ‘e’: cout<<“processing employee”; break;default: cout << “Quitting program”; break;

}

Page 32: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

32

switch in Practice…ATM menu loopdo {menu(); // display menucin>>choice;switch(choice){

case 'B': balance(userID);break;

case 'T‘: totalBalance(); break;default:cout<<"Command

notvailable”;}

} while(choice !='Q');

Use break to avoid

“falling through”

Page 33: 1 Simple File I/O Chapter 11 Switch Statement Chapter 12

33

Finally !!! … THE END