Make your own free website on Tripod.com

Tutorial 13

Sequential Access Files

 The instructor’s notes for this tutorial will consist of the following:

Overview

This tutorial will cover the basic concepts and implementation involved with sequential access files. Even though sequential access files have been used in previous tutorials to send output to, their use will be expanded a great deal in this tutorial. Topics will include opening and closing, writing information to, reading information from, and testing for end of sequential access files. Consuming characters and including delimiter characters will also be covered.

Objectives

After completing the tutorial, the student will be able to:

Lecture Notes

Introduction to data files

In addition to saving the C++ program instructions in a file, called a program file, you also can save input data in a file, called a data file. The information in a data file typically is organized into fields and records. A field is a single item of information about a person, place, or thing. A record is a group of related fields that contains all of the necessary data about a specific person, place, or thing. A data file is a collection of related records.

In most programming languages, you can create three different types of data files: sequential, random, and binary. The data file type refers to how the data is accessed. The data in a sequential file is always accessed sequentially (in consecutive order). The data in a random file, on the other hand, can be accessed either in consecutive order or in random order. The data in a binary file access file can be accessed by its byte location in the file. This tutorial (as well as the textbook) only covers sequential access files.

Introduction to sequential access files

Since sequential files are accessed in consecutive order, they can be considered similar to a cassette tape. Just like each piece of data in a sequential file must be accessed in consecutive order, each song on a cassette tape must also be accessed in consecutive order. To skip to the last piece of data in a sequential file, you must process through the data between where you currently are and the end of the file. The same is true with a cassette tape when you fast-forward to the last song on the tape.

Sequential files have a definite advantage in that they are very easily created. The major disadvantage to sequential files goes back to the cassette tape analogy - they are processed in consecutive order regardless of how you would like them to be processed. Therefore, sequential files work best when you want to process either a small file (100 records or less), or a large file whose records are always processed in consecutive order.

Creating and opening a sequential access data file

Sequential files can be either input data files or output data files. Input data files are those whose contents are read by a program, and output data files are those to which a program writes data. However, before a sequential file can be written to or read from, it must be created and opened.

For a program to use a sequential file, it must include the fstream header file. You will use the ifstream and ofstream classes, which are defined in the fstream header file, to create input or output file objects, respectively (these file objects are used to represent the actual files stored on your computer’s hard disk). The syntax for creating file objects is as follows:

ifstream.object; (for creating input file objects)

ofstream.object; (for creating output file objects)

where object is the name of the file object you would like to create. Note that naming file objects follow the same rules as naming variables (review if necessary). See figure 13-2 on page 450 for examples of creating input and output file objects.

After creating the file object, you then will use the C++ open function to open the file for either input, output, or append purposes. The open function is a public member function defined in both the ifstream and ofstream classes, and is therefore available to you to use. The syntax of the open function is as follows:

object.open(filename LEFTSQUARE,modeRIGHTSQUARE);

where object is the file object you previously created, filename is the actual name of the file you wish to open on your computer’s hard disk, and mode (optional) represents the file mode (see Figure 13-3 on page 450 for a list of permitted file modes for sequential files). Notice that ios:: appears in each mode shown in Figure 13-3. The two colons (::), called the scope resolution operator, indicate that the in, out, and app keywords, which follow the scope resolution operator in each mode, are defined in the ios class. The ios class is the base class that defines all input/output operations in C++.

See Figure 13-4 on page 451 for examples of opening various types of files in various modes.

Determining whether a file was opened successfully

Before attempting either to read data from or write data to a file, you always should verify that the data file was opened successfully. You can use the C++ is_open function, which is defined in both the ifstream and ofstream classes, to test if the file was opened successfully. The is_open function returns the value true if the open function was able to open the file, and returns false if the open function was not able to successfully open the file. You typically test the file immediately after opening it. Below is the syntax for the C++ is_open function:

object.is_open()

where object is the file object you just opened. See figure 13-6 on page 454 for an example of using the C++ is_open function.

Closing a file

When a program is finished with a data file, you should use the C++ close function, which is defined in both the ifstream and ofstream classes, to close it. Failing to close an open data file can result in the loss of data. Below is the syntax for the C++ close function, where object is the name of the file object to close:

object.close(); (See Figure 13-7 on page 455 for examples of the C++ close function)

Writing records to a sequential access data file

Remember from earlier tutorials that the syntax for displaying an item of data on the screen is object << data << endl;, where the object is cout, which represents the monitor. The syntax for writing a record to a sequential access data file is similar to this, except we will replace cout with the name of the file object that we would like the data written to.

Notice that to distinguish one record from another in a file, programmers usually write each record on a separate line in the file. You do so in C++ by including the endl stream manipulator at the end of the statement that writes the record to the file. The endl stream manipulator accomplishes this by writing an invisible character, known as the newline character, at the end of each record. The newline character, which is designated as ‘\n’ in C++, advances the cursor to the next line in the file immediately after a record is written.

If the record contains more than one field, C++ programmers use a character to separate the data in one field from the data in another field. The most commonly used character to accomplish this is the ‘#’ character. Figure 13-8 on page 456 shows examples of writing records to a sequential access data file using all of the syntax listed above.

The ignore function

In some programs, you may need the computer to disregard, of skip, characters entered at the keyboard or read from a data file. In a C++ program, you instruct the computer to disregard characters using the ignore function. The function actually reads and then disregards the characters (or consumes them). The syntax of the ignore functions is as follows:

object.ignore(LEFTSQUAREnCountRIGHTSQUARE LEFTSQUARE,delimCharacterRIGHTSQUARE);

where

Note that a common delimeter character used when reading characters from the keyboard is the newline character, while the common delimeter character used when reading characters from a data file is EOF (which represents the end of the data file). See Figure 13-9 on page 458 for examples of using the ignore function.

records from a sequential access file

Remember from earlier tutorials that the syntax for obtaining a string of data from the keyboard is getline(object, variable);, where the object is cin, which represents the keyboard. The syntax for reading a record from a sequential access data file is similar to this, except we will replace cin with the name of the file object that we would like to read the data from, and add a parameter for a delimeter character. The new syntax will look like the following: getline(object, variable LEFTSQUARE,delimCharacterRIGHTSQUARE );

where

Also note that when reading records from a data file, the C++ eof function is used to test for the end of file. The eof function returns true if the program attempts to read past the end of the file, otherwise it returns false. See Figures 13-11 and 13-12 on pages 462-463 and 465, respectively, for examples of reading data from a file.

 

Solutions to Questions

1. b field

2. d record

3. b fstream

4. c ofstream

5. b ofstream outPayroll;

6. d both a and b

7. c ios::app

8. a close

9. a is_open

10. c outFile << city << endl;

11. c inFile >> salary;

12. d outFile << city << ‘#’ << state << endl;

13. c while(!inFile.eof())

14. b ifstream inPayroll;

15. d both b and c

16. d inFile.ignore(1);

Solutions to Concept Lesson Exercises

1.

Input

Processing

Output

letters of the

alphabet from

a to z

Processing items:

letter

counter

Algorithm:

  1. open output file
  2. if(open was successful)

initialize counter to 1

repeat while(counter <= 26)

prompt user for letter of alphabet

write letter entered to output file

add 1 to counter

end repeat while

else

display message indicating that file was not opened successfully

end if

letters of the alphabet from a to z saved in a sequential access file

 

//T13ConE01.cpp - writes 26 letters to a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//open output file

ofstream outFile;

outFile.open("T13ConE01 - solution.dat", ios::out);

//declare variables

char letter = ' ';

int counter = 1;

//determine if open was successful

if(outFile.is_open()) //if open was successful

{

//write records to file

while (counter <= 26)

{

cout << "Enter a letter: ";

cin >> letter;

outFile << letter << endl;

counter = counter + 1;

} //end while

//close file

outFile.close();

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

Contents of the T13ConE01-Solution.dat file

a

b

c

d

e

f

g

h

i

j

k

l

m

n

o

p

q

r

s

t

u

v

w

x

y

z

2.

Input

Processing

Output

numbers from 1 through 25

Processing items:

counter

Algorithm:

  1. open output file
  2. if(open was successful)

initialize counter to 1

repeat while(counter <= 25)

write the square of the counter to the output file

add 1 to counter

end repeat while

else

display message indicating that file was not opened successfully

end if

squares of the numbers from 1 through 25 saved in a sequential access output file

 //T13ConE02.cpp - writes the squares of the numbers from

//1 through 25 to a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//open output file

ofstream outFile;

outFile.open("T13ConE02 - solution.dat", ios::out);

//declare variables

int counter = 1;

//determine if open was successful

if(outFile.is_open()) //if open was successful

{

//write records to file

while (counter <= 25)

{

outFile << counter * counter << endl;

counter = counter + 1;

} //end while

//close file

outFile.close();

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

Contents of the T13ConE02 – Solution.dat file

1

4

9

16

25

36

49

64

81

100

121

144

169

196

225

256

289

324

361

400

441

484

529

576

625

3.

Input

Processing

Output

weekly total payroll

Processing items: none

Algorithm:

  1. open output file
  2. if(open was successful)

get first weekly total payroll

repeat while(weekly total payroll > 0)

write the weekly total payroll to the output file

get next weekly total payroll

end repeat while

else

display message indicating that file was not opened successfully

end if

weekly total payroll saved in a sequential access output file

//T13ConE03.cpp - writes weekly payroll amounts to a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//open output file

ofstream outFile;

outFile.open("T13ConE03 - solution.dat", ios::app);

//declare variable

float payroll = 0.0;

//determine if open was successful

if(outFile.is_open()) //if open was successful

{

cout << "Enter weekly payroll amount: ";

cin >> payroll;

//write records to file

while (payroll > 0)

{

outFile << fixed;

outFile.precision(2);

outFile << payroll << endl;

cout << "Enter weekly payroll amount: ";

cin >> payroll;

} //end while

//close file

outFile.close();

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

 

Contents of the T13ConE03 – Solution.dat file

25000.89

35600.50

45678.99

67000.56

4.

Input

Processing

Output

prices

Processing items: none

Algorithm:

  1. open output file
  2. if(open was successful)

get first price

repeat while(price > 0)

write the price to the output file

get next price

end repeat while

else

display message indicating that file was not opened successfully

end if

prices saved in a sequential access output file

 

//T13ConE04.cpp - writes prices to a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//open output file

ofstream outFile;

outFile.open("T13ConE04 - solution.dat", ios::app);

//declare variable

float price = 0.0;

//determine if open was successful

if(outFile.is_open()) //if open was successful

{

cout << "Enter price: ";

cin >> price;

//write records to file

while (price > 0)

{

outFile << fixed;

outFile.precision(2);

outFile << price << endl;

cout << "Enter price: ";

cin >> price;

} //end while

//close file

outFile.close();

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

 

Contents of the T13ConE04 – Solution.dat file

10.50

15.99

20.00

76.54

17.34

5.

Input

Processing

Output

letters stored in a sequential access file

Processing items: none

Algorithm:

  1. open input file
  2. if(open was successful)

initialize counter to 0

read first letter

repeat while(it is not end of file)

add 1 to counter

read next letter

end repeat while

display counter

else

display message indicating that file was not opened successfully

end if

counter (number of letters)

//T13ConE05.cpp - displays the number of letters

//contained in a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//open input file

ifstream inFile;

inFile.open("T13ConE05 - Solution.dat", ios::in);

//declare variables

char letter = ' ';

int counter = 0;

//determine if open was successful

if(inFile.is_open()) //if open was successful

{

//read records from file

inFile >> letter;

while (!inFile.eof())

{

counter = counter + 1;

inFile >> letter;

} //end while

//close file

inFile.close();

//display number of letters

cout << counter << " letters are contained in the file." << endl;

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

Contents of the T13ConE05 – Solution.dat file

a

b

c

d

e

f

g

h

i

j

k

l

m

n

o

p

q

r

s

t

u

v

w

x

y

z

6.

Input

Processing

Output

numbers stored in a sequential access file

Processing items: none

Algorithm:

  1. open input file
  2. if(open was successful)

initialize accumulator to 0

read first number

repeat while(it is not end of file)

add number to accumulator

read next number

end repeat while

display accumulator

else

display message indicating that file was not opened successfully

end if

accumulator (sum of numbers)

 //T13ConE06.cpp - displays the sum of the numbers

//contained in a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//open input file

ifstream inFile;

inFile.open("T13ConE06 - Solution.dat", ios::in);

//declare variables

int number = 0;

int sum = 0;

//determine if open was successful

if(inFile.is_open()) //if open was successful

{

//read records from file

inFile >> number;

while (!inFile.eof())

{

sum = sum + number;

inFile >> number;

} //end while

//close file

inFile.close();

//display sum of numbers

cout << "Sum: " << sum << endl;

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

Contents of the T13ConE06 – Solution.dat file

1

4

9

16

25

36

49

64

81

100

121

144

169

196

225

256

289

324

361

400

441

484

529

576

625

 7.

Input

Processing

Output

weekly payroll amounts stored in a sequential access file

Processing items: none

Algorithm:

  1. open input file
  2. if(open was successful)

initialize accumulator to 0

read first weekly payroll amount

repeat while(it is not end of file)

add weekly payroll amount to accumulator

read next weekly payroll amount

end repeat while

display accumulator

else

display message indicating that file was not opened successfully

end if

accumulator (sum of weekly payroll amounts)

//T13ConE07.cpp - displays the sum of the weekly payroll

//amounts contained in a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//open input file

ifstream inFile;

inFile.open("T13ConE07 - Solution.dat", ios::in);

//declare variables

float payroll = 0.0;

float sum = 0.0;

//determine if open was successful

if(inFile.is_open()) //if open was successful

{

//read records from file

inFile >> payroll;

while (!inFile.eof())

{

sum = sum + payroll;

inFile >> payroll;

} //end while

//close file

inFile.close();

//display total payroll

cout << fixed;

cout.precision(2);

cout << "Total payroll: " << sum << endl;

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

 

Contents of the T13ConE07 – Solution.dat file

25000.89

35600.50

45678.99

67000.56

8.

Input

Processing

Output

prices stored in a sequential access file

Processing items:

counter

accumulator

Algorithm:

  1. open input file
  2. if(open was successful)

initialize counter to 0

initialize accumulator to 0

read first price

repeat while(it is not end of file)

add 1 to counter

add price to accumulator

read next price

end repeat while

if (counter > 0)

calculate average price by dividing the accumulator by the counter

display average price

else

display error message

end if

else

display message indicating that file was not opened successfully

end if

average price

 //T13ConE08.cpp - displays the average price

//contained in a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//open input file

ifstream inFile;

inFile.open("T13ConE08 - Solution.dat", ios::in);

//declare variables

float price = 0.0;

int counter = 0;

float sum = 0.0;

//determine if open was successful

if(inFile.is_open()) //if open was successful

{

//read records from file

inFile >> price;

while (!inFile.eof())

{

counter = counter + 1;

sum = sum + price;

inFile >> price;

} //end while

//close file

inFile.close();

if (counter > 0)

{

//calculate and display average price

cout << fixed;

cout.precision(2);

cout << "Average price: " << sum / counter << endl;

}

else

cout << "File is empty." << endl;

//end if

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

 

Contents of the T13ConE08 – Solution.dat file

10.50

15.99

20.00

76.54

17.34

9.

Input

Processing

Output

code

salary

Processing items:

counter

Algorithm:

  1. open output file
  2. if(open was successful)

initialize counter to 1

get code and salary

repeat while(counter <= 5)

write code and salary to file

add 1 to counter

get code and salary

end repeat while

else

display message indicating that file was not opened successfully

end if

codes and salaries saved in a sequential access output file

//T13ConE09.cpp - writes codes and salaries to a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//open output file

ofstream outFile;

outFile.open("T13ConE09 - solution.dat", ios::out);

//declare variables

char code = ' ';

int salary = 0;

int count = 1;

//determine if open was successful

if(outFile.is_open()) //if open was successful

{

//write records to file

while (count <= 5)

{

cout << "Enter code: ";

cin >> code;

code = toupper(code);

cout << "Enter salary: ";

cin >> salary;

outFile << code << '#' << salary << endl;

count = count + 1;

} //end while

//close file

outFile.close();

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

 

Contents of the T13ConE09 – Solution.dat file

A#27200

B#15000

C#23000

D#12000

E#25500

10.

Input

Processing

Output

number

quantity

price

Processing items: none

Algorithm:

  1. open output file
  2. if(open was successful)

get number

repeat while(number is not X)

convert number to uppercase

get quantity and price

write number, quantity, and price to file

get number

end repeat while

else

display message indicating that file was not opened successfully

end if

number, quantity, and price saved in a sequential access output file

//T13ConE10.cpp - writes inventory numbers, quantities, and

//prices to a sequential access file

#include <iostream>

#include <fstream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

//open output file

ofstream outFile;

outFile.open("T13ConE10 - solution.dat", ios::out);

//declare variables

string invNum = "";

int quantity = 0;

int price = 0;

//determine if open was successful

if(outFile.is_open()) //if open was successful

{

cout << "Enter inventory number: ";

getline(cin, invNum);

//write records to file

while (invNum != "X" && invNum != "x")

{

transform(invNum.begin(), invNum.end(), invNum.begin(), toupper);

cout << "Enter quantity: ";

cin >> quantity;

cout << "Enter price: ";

cin >> price;

cin.ignore(1);

outFile << invNum << '#' << quantity << "#" << price << endl;

cout << "Enter inventory number: ";

getline(cin, invNum);

} //end while

//close file

outFile.close();

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

 

Contents of the T13ConE10 – Solution.dat file

20AB#400#5

30CD#550#9

45XX#600#20

 11.

Input

Processing

Output

codes and salaries stored in a seqential access file

Processing items: none

Algorithm:

  1. open input file
  2. if(open was successful)

read code and salary

repeat while(it is not end of the file)

display code and salary

read code and salary

end repeat while

else

display message indicating that file was not opened successfully

end if

codes and salaries

//T13ConE11.cpp - displays the codes and salaries

//contained in a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//open input file

ifstream inFile;

inFile.open("T13ConE11 - Solution.dat", ios::in);

//declare variables

char code = ' ';

int salary = 0;

//determine if open was successful

if(inFile.is_open()) //if open was successful

{

//read records from file

inFile >> code;

inFile.ignore(1);

inFile >> salary;

inFile.ignore(1);

while (!inFile.eof())

{

cout << code << " " << salary << endl;

inFile >> code;

inFile.ignore(1);

inFile >> salary;

inFile.ignore(1);

} //end while

//close file

inFile.close();

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

 

Contents of the T13ConE11 – Solution.dat file

A#27200

B#15000

C#23000

D#12000

E#25500

12.

Input

Processing

Output

numbers, quantities, and prices stored in a sequential access file

Processing items: none

Algorithm:

  1. open input file
  2. if(open was successful)

read number, quantity, and price

repeat while(it is not end of the file)

multiply quantity by price, and add result to total dollar value

read number, quantity, and price

end repeat while

display total dollar value

else

display message indicating that file was not opened successfully

end if

total dollar value

//T13ConE12.cpp - displays the total dollar value of

//the items contained in a sequential access file

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main()

{

//open input file

ifstream inFile;

inFile.open("T13ConE12 - Solution.dat", ios::in);

//declare variables

string number = "";

int quantity = 0;

int price = 0;

int totalDol = 0;

//determine if open was successful

if(inFile.is_open()) //if open was successful

{

//read records from file

getline(inFile, number, '#');

inFile >> quantity;

inFile.ignore(1);

inFile >> price;

inFile.ignore(1);

while (!inFile.eof())

{

totalDol = totalDol + quantity * price;

getline(inFile, number, '#');

inFile >> quantity;

inFile.ignore(1);

inFile >> price;

inFile.ignore(1);

} //end while

//close file

inFile.close();

//display total dollar value

cout << "Total dollar value: " << totalDol << endl;

}

else //open failed

cout << "Error opening file." << endl;

//end if

return 0;

}//end of main function

 

Contents of the T13ConE12 – Solution.dat file

20AB#400#5

30CD#550#9

45XX#600#20

 

13.

//T13ConE13.cpp - displays a name and bonus amount

#include <iostream>

#include <string>

using namespace std;

int main()

{

string name = "";

float sales = 0.0;

float bonus = 0.0;

cout << "Salesperson name: ";

getline(cin, name);

while (name != "X" && name != "x")

{

cout << "Sales: ";

cin >> sales;

cin.ignore(1);

bonus = sales * .15;

cout << "Bonus: " << bonus << endl;

cout << "Salesperson name: ";

getline(cin, name);

} //end while

return 0;

} //end of main function

14. Changes made to the original code are shaded

//T13ConE14.cpp - saves numbers to a file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//declare variable

int num = 0;

//open file for output

ofstream outFile;

outFile.open("T13ConE14.dat", ios::out);

//determine if open was successful

if (outFile.is_open()) //open was successful

{

//enter and save records

cout << "Enter number (enter a negative number to quit): ";

cin >> num;

while (num >= 0)

{

outFile << num << endl;

cout << "Enter number (enter a negative number to quit): ";

cin >> num;

} //end while

//close file

outFile.close();

}

else

cout << "Open was not successful." << endl;

//end if

return 0;

} //end of main function

 

 

Contents of the T13ConE14 – Solution.dat file

7

10

6

 

Solutions to Application Lesson Exercises

(Answers to exercises may vary)

1.

//T13AppE01 - defines the EmployCodes class

#include <fstream>

using namespace std;

//*****declaration section*****

class EmployCodes

{

public:

EmployCodes();

void readRecord(ifstream &);

char getCode();

int getSalary();

private:

char code;

int salary;

};

//*****implementation section*****

EmployCodes::EmployCodes()

{

code = ' ';

salary = 0;

} //end of default constructor

void EmployCodes::readRecord(ifstream &inF)

{

inF >> code;

inF.ignore(1);

inF >> salary;

inF.ignore(1);

} //end of readRecord function

char EmployCodes::getCode()

{

return code;

} //end of getCode function

int EmployCodes::getSalary()

{

return salary;

} //end of getSalary function

//T13AppE01.cpp - displays codes and salaries

#include <iostream>

#include <fstream>

#include "c:\cpp\myclasses\t13appe01 - solution"

using namespace std;

int main()

{

//declare EmployCodes object

EmployCodes codeSalary;

//declare file object, then open file

ifstream inFile;

inFile.open("t13appe01 - solution.dat", ios::in);

//determine if open was successful

if (inFile.is_open())

{

//if open was successful, read and display records, then close file

cout << "Code Salary" << endl;

codeSalary.readRecord(inFile);

while (!inFile.eof())

{

cout << codeSalary.getCode() << " "

<< codeSalary.getSalary() << endl;

codeSalary.readRecord(inFile);

} //end while

inFile.close();

}

else

//otherwise, display message indicating that the file was not opened

cout << "File was not opened." << endl;

//end if

return 0;

} //end of main function

 

Contents of T13AppE01 – Solution.dat file

A#27200

B#15000

C#23000

D#12000

E#25500

 2.

//T13AppE02 - defines the EmployCodes class

#include <fstream>

using namespace std;

//*****declaration section*****

class EmployCodes

{

public:

EmployCodes();

void readRecord(ifstream &);

char getCode();

int getSalary();

private:

char code;

int salary;

};

//*****implementation section*****

EmployCodes::EmployCodes()

{

code = ' ';

salary = 0;

} //end of default constructor

void EmployCodes::readRecord(ifstream &inF)

{

inF >> code;

inF.ignore(1);

inF >> salary;

inF.ignore(1);

} //end of readRecord function

char EmployCodes::getCode()

{

return code;

} //end of getCode function

int EmployCodes::getSalary()

{

return salary;

} //end of getSalary function

//T13AppE02.cpp - displays codes and salaries

#include <iostream>

#include <fstream>

#include "c:\cpp\myclasses\t13appe02 - solution"

using namespace std;

int main()

{

//declare EmployCodes object

EmployCodes codeSalary;

//declare variable

char salaryCode = ' ';

//declare file object, then open file

ifstream inFile;

inFile.open("t13appe02 - solution.dat", ios::in);

//determine if open was successful

if (inFile.is_open())

{

//if open was successful, get code, display salary, then close file

cout << "Enter the code: ";

cin >> salaryCode;

codeSalary.readRecord(inFile);

while (!inFile.eof() && toupper(salaryCode) != toupper(codeSalary.getCode()))

codeSalary.readRecord(inFile);

//end while

if (!inFile.eof())

cout << "Salary: " << codeSalary.getSalary() << endl;

else

cout << "Invalid code" << endl;

//end if

inFile.close();

}

else

//otherwise, display message indicating that the file was not opened

cout << "File was not opened." << endl;

//end if

return 0;

} //end of main function

 

Contents of T13AppE02 – Solution.dat file

A#27200

B#15000

C#23000

D#12000

E#25500

 3.

//T13AppE03 - defines the AddressInfo class

#include <fstream>

#include <algorithm>

#include <string>

using namespace std;

//*****declaration section*****

class AddressInfo

{

public:

AddressInfo();

int assignData(string, string);

void writeRecord(ofstream &);

private:

string zipCode;

string city;

};

//*****implementation section*****

AddressInfo::AddressInfo()

{

zipCode = "";

city = "";

} //end of default constructor

int AddressInfo::assignData(string z, string c)

{

int dataOk = 0;

if (z.size() == 5)

{

zipCode = z;

transform(c.begin(), c.end(), c.begin(), toupper);

city = c;

dataOk = 1;

} //end if

return dataOk;

} //end of assignData function

void AddressInfo::writeRecord(ofstream &outF)

{

outF << zipCode << '#' << city << endl;

} //end of writeRecord function

 

//T13AppE03.cpp - writes zip codes and cities to a

//sequential access file

#include <iostream>

#include <fstream>

#include <string>

#include "c:\cpp\myclasses\t13appe03 - solution"

using namespace std;

int main()

{

//declare AddressInfo object

AddressInfo address;

//declare variables

string zip = "";

string name = "";

int valid = 0;

//declare file object, then open file

ofstream outFile;

outFile.open("t13appe03.dat - solution", ios::app);

//determine if open was successful

if (outFile.is_open())

{

//if open was successful, get zip code and city, assign info

//to record, write record (if valid)

cout << "Enter the zip code (X to exit program): ";

getline(cin, zip);

while (zip != "X" && zip != "x")

{

cout << "Enter the city name: ";

getline(cin, name);

valid = address.assignData(zip, name);

if (valid == 1)

address.writeRecord(outFile);

else

cout << "Zip code error" << endl;

//end if

cout << "Enter the zip code (X to exit program): ";

getline(cin, zip);

} //end while

//close file

outFile.close();

}

else

//otherwise, display message indicating that the file was not opened

cout << "File was not opened." << endl;

//end if

return 0;

} //end of main function

Contents of T13AppE03 – Solution.dat file

60561#DARIEN

60544#HINSDALE

60137#GLEN ELLYN

60135#DOWNERS GROVE

60136#BURR RIDGE

4.

//T13AppE04.cpp - displays names corresponding to a code

//entered by the user

#include <iostream>

#include <fstream>

#include <algorithm>

#include <string>

using namespace std;

int main()

{

//declare variables

string name = "";

string code = "";

string searchFor = "";

//open input file

ifstream inFile;

inFile.open("t13appe04 - solution.dat", ios::in);

//determine if open was successful

if(inFile.is_open())

{

cout << "Enter the code (F1, F2, P1, P2): ";

getline(cin, searchFor);

transform(searchFor.begin(), searchFor.end(), searchFor.begin(), toupper);

//read first record

getline(inFile, name, '#');

getline(inFile, code);

while(!inFile.eof())

{

transform(code.begin(), code.end(), code.begin(), toupper);

if (code == searchFor)

cout << name << endl;

//end if

getline(inFile, name, '#');

getline(inFile, code);

}//end while

inFile.close();

}

else

cout << "Error opening file" << endl;

//end if

return 0;

}//end of main function

Contents of the T13AppE04 – Solution.dat file

Joe Smith#F1

Mary Jones#F2

Joel Adkari#F2

Sue Lin#P1

Vicky Li#P2

Jack Light#P1

Paul Loomis#F1

Linda Lane#P1

Janice Paulo#F2

5.

//T13AppE05.cpp - updates a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//declare variables

int num = 0;

//open input file

ifstream inFile;

inFile.open("t13appe05 - solution.dat", ios::in);

//open output file

ofstream outFile;

outFile.open("t13appe05 - solution.new", ios::out);

//determine if open was successful

if(inFile.is_open() && outFile.is_open())

{

//read first record

inFile >> num;

while(!inFile.eof())

{

//place new value in output file

outFile << num + 1 << endl;

//read next record

inFile >> num;

}//end while

//close files

inFile.close();

outFile.close();

}

else

cout << "Error opening file" << endl;

//end if

return 0;

}//end of main function

Contents of the T13AppE05 – Solution.dat file

10

11

12

13

14

15

 

Contents of the T13AppE05 – Solution.new file

11

12

13

14

15

16

 6.

//T13AppE06.cpp - writes the even numbers from one sequential

//access file to another sequential access file

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//declare variable

int num = 0;

//open input file

ifstream inFile;

inFile.open("t13appe06 - solution.dat", ios::in);

//open output file

ofstream outFile;

outFile.open("t13appe06 - solution.new", ios::out);

//determine if open was successful

if(inFile.is_open() && outFile.is_open())

{

//read first record

inFile >> num;

while(!inFile.eof())

{

//place new value in output file if even number

if ( (num % 2) == 0)

outFile << num << endl;

//read next record

inFile >> num;

}//end while

//close files

inFile.close();

outFile.close();

}

else

cout << "Error opening file" << endl;

//end if

return 0;

}//end of main function

Contents of T13AppE06 – Solution.dat file

1

2

3

4

19

18

12

14

55

84

 

Contents of T13AppE06 – Solution.new file

2

4

18

12

14

84

 7.

//T13AppE07 - defines the EmployCodes class

#include <fstream>

using namespace std;

//*****declaration section*****

class EmployCodes

{

public:

EmployCodes();

void readRecord(ifstream &);

char getCode();

int getSalary();

private:

char code;

int salary;

};

//*****implementation section*****

EmployCodes::EmployCodes()

{

code = ' ';

salary = 0;

} //end of default constructor

void EmployCodes::readRecord(ifstream &inF)

{

inF >> code;

inF.ignore(1);

inF >> salary;

inF.ignore(1);

} //end of readRecord function

char EmployCodes::getCode()

{

return code;

} //end of getCode function

int EmployCodes::getSalary()

{

return salary;

} //end of getSalary function

//T13AppE07.cpp - displays codes and salaries

#include <iostream>

#include <fstream>

#include <string>

#include "c:\cpp\myclasses\t13appe07 - solution"

using namespace std;

int main()

{

//declare EmployCodes object

EmployCodes codeSalary;

//declare variables

char salaryCode = ' ';

string another = "Y";

//declare file object

ifstream inFile;

while (another == "Y" || another == "y")

{

inFile.open("t13appe07 - solution.dat", ios::in);

//determine if open was successful

if (inFile.is_open())

{

//if open was successful, get code, display salary, then close file

cout << "Enter the code: ";

cin >> salaryCode;

cin.ignore(100, '\n');

codeSalary.readRecord(inFile);

while (!inFile.eof() && toupper(salaryCode) != toupper(codeSalary.getCode()))

codeSalary.readRecord(inFile);

//end while

if (!inFile.eof())

cout << "Salary: " << codeSalary.getSalary() << endl;

else

cout << "Invalid code" << endl;

//end if

inFile.close();

}

else

//otherwise, display message indicating that the file was not opened

cout << "File was not opened." << endl;

//end if

cout << "Enter another code (Y/N)? ";

getline(cin, another);

} //end while

return 0;

} //end of main function

 Contents of T13AppE07 – Solution.dat file

A#27200

B#15000

C#23000

D#12000

E#25500

 8. Changes to the original code are shaded.

//T13AppE08 - defines the Item class

#include <fstream>

#include <string>

using namespace std;

//*****declaration section*****

class Item

{

public:

Item();

void readRecord(ifstream &);

string getName();

int getQuantity();

int getPrice();

private:

string name;

int quantity;

int price;

};

//*****implementation section*****

Item::Item()

{

name = "";

quantity = 0;

price = 0;

} //end of default constructor

void Item::readRecord(ifstream &inF)

{

getline(inF, name, '#');


inF >> quantity;

inF.ignore(1);

inF >> price;

inF.ignore(1);

} //end of readRecord function

string Item::getName()

{

return name;

} //end of getName function

int Item::getQuantity()

{

return quantity;

} //end of getQuantity function

int Item::getPrice()

{

return price;

} //end of getPrice function

  Changes to the original code are shaded.

//T13AppE08.cpp - reads and displays records

#include <iostream>

#include <fstream>

#include "c:\cpp\myclasses\t13appe08"

using namespace std;

int main()

{

//declare Item object

Item inventory;

//open file

ifstream inFile;

inFile.open("t13appe08.dat", ios::in);

//read and display records

inventory.readRecord(inFile);

while (!inFile.eof())

{

cout << inventory.getName() << " "

<< inventory.getQuantity() << " "

<< inventory.getPrice() << endl;

inventory.readRecord(inFile);

} //end while

inFile.close();

return 0;

} //end of main function

Contents of the T13AppE08 – Solution.dat file

desk#20#100

table#45#125

chair#100#55

lamp#10#20