0% found this document useful (0 votes)
19 views15 pages

Lab 12, FA20-BEE-224

The document outlines several C++ programs that handle file input/output operations for payroll and student grade management. It includes detailed explanations of the code structure, functions, and processes for reading data from files, calculating values, and writing outputs to new files. Key functionalities include error handling for file operations and formatting output for readability.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views15 pages

Lab 12, FA20-BEE-224

The document outlines several C++ programs that handle file input/output operations for payroll and student grade management. It includes detailed explanations of the code structure, functions, and processes for reading data from files, calculating values, and writing outputs to new files. Key functionalities include error handling for file operations and formatting output for readability.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Task # 1

Program:- Description:-
#include <fstream> Explanation
#include <iostream> Defining payfile as an input file:
#include <iomanip>
using namespace std; The line ifstream payfile; defines payfile as an
input file stream.
int main() {
// Define payfile as an input file Opening payfile and attaching it to payroll.dat:
ifstream payfile;
The line payfile.open("payroll.dat"); opens the file
float gross; named payroll.dat.
float net;
float hours; Checking if payfile does not exist:
float payRate;
float stateTax; The condition if (!payfile) checks if the file could
float fedTax; not be opened,

cout << fixed << setprecision(2) << showpoint; indicating that it might not exist.

// Open payfile and attach it to the physical file Priming the read for the payfile:
named payroll.dat
payfile.open("payroll.dat"); The line payfile >> hours >> payRate >> stateTax
>> fedTax;
// Check if payfile does not exist
if (!payfile) { reads the first set of values from the file.
cout << "Error opening file. \n";
cout << "It may not exist where indicated" Loop condition to run while payfile has more
<< endl; data:
return 1;
} The while (payfile) loop continues processing as
long as there are more data to read.
cout << "Pay Rate" << setw(10) << "Hours" <<
setw(15) << "Gross Pay" << setw(12) << "Net Calculating gross and net pay:
Pay" << endl << endl;
Inside the loop, gross = payRate * hours;
// Prime the read for the payfile
payfile >> hours >> payRate >> stateTax >> and net = gross - (gross * stateTax) - (gross *
fedTax; fedTax); calculate the gross and net pay,
respectively.
// Loop while payfile has more data to process
while (payfile) { Reading the next set of values:
gross = payRate * hours;
net = gross - (gross * stateTax) - (gross * The line payfile >> hours >> payRate >> stateTax
fedTax); >> fedTax; inside the loop primes the next read
cout << payRate << setw(10) << hours << operation.
setw(15) << gross << setw(12) << net << endl; This program reads the payroll.dat file, processes
each employee's data, and outputs their pay
// Read the next set of values from the file information, handling any issues with file
payfile >> hours >> payRate >> stateTax >> existence.
fedTax;
}

payfile.close();
return 0;
}

Output:-
Task #2

Program:- Description:-
#include <fstream>
#include <iostream> Explanation of Changes
#include <iomanip>
using namespace std; Output File Stream: Added ofstream

int main() { outfile("pay.out"); to create and open the output


// Define payfile as an input file file pay.out.
ifstream payfile("payroll.dat");
ofstream outfile("pay.out"); Redirected Output: Changed cout statements to
outfile to write output to the file instead of the
float gross; console.
float net;
float hours; Steps to Run the Program
float payRate;
float stateTax; Create the Data File: Ensure the payroll.dat file
float fedTax; with the specified data is in the same directory as
the .cpp file.
// Check if payfile does not exist
if (!payfile) { Compile and Run the Program: Compile and run
cout << "Error opening file. \n"; the modified program.
cout << "It may not exist where indicated"
<< endl; This will create a file named pay.out in the same
return 1; directory.
}
Check the Output File: Open the pay.out file to
outfile << fixed << setprecision(2) << verify the output.
showpoint;
outfile << "Pay Rate" << setw(10) << "Hours"
<< setw(15) << "Gross Pay" << setw(12) << "Net
Pay" << endl << endl;

// Prime the read for the payfile


payfile >> hours >> payRate >> stateTax >>
fedTax;

// Loop while payfile has more data to process


while (payfile) {
gross = payRate * hours;
net = gross - (gross * stateTax) - (gross *
fedTax);
outfile << payRate << setw(10) << hours <<
setw(15) << gross << setw(12) << net << endl;

// Read the next set of values from the file


payfile >> hours >> payRate >> stateTax >>
fedTax;
}

payfile.close();
outfile.close();
return 0;
}

Output:-
Pay Rate Hours Gross Pay Net Pay
15.00 40 600.00 492.00
10.00 50 500.00 420.00
12.50 60 750.00 615.00

Task # 3

Program:- Description:-
#include <iostream>
#include <iomanip> Explanation
#include <fstream> readit Function:
using namespace std;
This function reads records from the input file and
const int NAMESIZE = 15; stores them in the array of Grades structures
const int MAXRECORDS = 50; (gradeType).

struct Grades { It takes three parameters: an input file stream


char name[NAMESIZE + 1];
int test1; (ifstream& infile), the array of records (gradeType
int test2;
int final; records), and a reference to the number of records
}; (int& numRecords).

typedef Grades gradeType[MAXRECORDS]; Inside the function, a while loop reads each record
from the file and stores it in the
void readit(ifstream& infile, gradeType records,
int& numRecords); corresponding element of the array.

int main() { The number of records is incremented


ifstream indata; (numRecords++) after each successful read
indata.open("graderoll.dat"); operation.
int numRecord;
gradeType studentRecord; main Function:

if (!indata) { The program opens the input file "graderoll.dat"


cout << "Error opening file. \n"; and checks if it's successfully opened.
cout << "It may not exist where indicated"
<< endl; It calls the readit function to read records from the
return 1; file and store them in the studentRecord array.
} After reading the records, it outputs the
information in a formatted table-like manner.
// Call the function readit Output Formatting:
readit(indata, studentRecord, numRecord);
The output is formatted using setw to align
// Output the information columns neatly.
cout << setw(20) << left << "Name" <<
setw(10) << "Test 1" << setw(10) << "Test 2" << The header row is labeled with "Name", "Test 1",
setw(10) << "Final" << endl; "Test 2", and "Final".
for (int count = 0; count < numRecord; count+
+) { Each row represents a student's name along with
cout << setw(20) << left << their test and final exam grades.
studentRecord[count].name << setw(10)
<< studentRecord[count].test1 <<
setw(10) << studentRecord[count].test2
<< setw(10) << studentRecord[count].final
<< endl;
}

return 0;
}

void readit(ifstream& infile, gradeType records,


int& numRecords) {
numRecords = 0;
while (infile >> records[numRecords].name >>
records[numRecords].test1
>> records[numRecords].test2 >>
records[numRecords].final) {
numRecords++;
}
infile.close();
}

Output:-
Home Task # 1:-

Program:- Description:-
#include <iostream>
#include <iomanip> Explanation
#include <fstream> New Field letter:
using namespace std;
A new field letter of type char is added to the
const int NAMESIZE = 15; Grades structure to store the letter grade.
const int MAXRECORDS = 50;
calculateLetterGrade Function:
struct Grades {
char name[NAMESIZE + 1]; This function takes the test scores and final exam
int test1; score as parameters and calculates the average
int test2;
int final; grade using the specified weights (30% for each
char letter; // New field to hold the letter grade test and 40% for the final).
};
It then determines the letter grade based on the
typedef Grades gradeType[MAXRECORDS]; average and returns it.

void readit(ifstream& infile, gradeType records, Updating readit Function: After reading each
int& numRecords); record from the file,
char calculateLetterGrade(int test1, int test2, int
final); the calculateLetterGrade function is called to
determine the letter grade, which is then assigned
int main() { to the letter field of the Grades structure.
ifstream indata;
indata.open("graderoll.dat"); Output Formatting:
int numRecord;
gradeType studentRecord; The output is updated to include the new letter
field,
if (!indata) {
cout << "Error opening file. \n"; which displays the letter grade corresponding to
cout << "It may not exist where indicated" each student's average grade.
<< endl;
return 1;
}

// Call the function readit


readit(indata, studentRecord, numRecord);

// Output the information


cout << setw(20) << left << "Name" <<
setw(10) << "Test 1" << setw(10) << "Test 2" <<
setw(10) << "Final" << setw(10) << "Letter" <<
endl;
for (int count = 0; count < numRecord; count+
+) {
cout << setw(20) << left <<
studentRecord[count].name << setw(10)
<< studentRecord[count].test1 <<
setw(10) << studentRecord[count].test2
<< setw(10) << studentRecord[count].final
<< setw(10) << studentRecord[count].letter <<
endl;
}

return 0;
}

void readit(ifstream& infile, gradeType records,


int& numRecords) {
numRecords = 0;
while (infile >> records[numRecords].name >>
records[numRecords].test1
>> records[numRecords].test2 >>
records[numRecords].final) {
records[numRecords].letter =
calculateLetterGrade(records[numRecords].test1,
records[numRecords].test2,
records[numRecords].final);
numRecords++;
}
infile.close();
}

char calculateLetterGrade(int test1, int test2, int


final) {
// Calculate average grade with the specified
weights
double average = 0.3 * test1 + 0.3 * test2 + 0.4
* final;

// Determine letter grade based on the average


if (average >= 90)
return 'A';
else if (average >= 80)
return 'B';
else if (average >= 70)
return 'C';
else if (average >= 60)
return 'D';
else
return 'F';
}

Output:-
Task # 2

Program:- Description:-
#include <fstream> This C++ program, named "budget.cpp", is
#include <iostream> designed to manage financial information for
#include <iomanip> individuals. Here's a breakdown of its
using namespace std; functionality:

const int NAMESIZE = 15; 1. Header Files: The program includes necessary
header files like `<fstream>` for file handling,
struct budget { `<iostream>` for standard input-output operations,
char name[NAMESIZE + 1]; and `<iomanip>` for setting output formatting.
float income; // person's monthly income
float rent; // person's monthly rent 2. Constants and Structure Definition:
float food; // person's monthly food bill - `NAMESIZE` is defined as 15, representing
float utilities; // person's monthly utility bill the maximum size of a person's name.
float miscell; // person's other bills - The `budget` structure is defined to hold
float net; // person's net money after bills financial information, including name, income,
are paid rent, food costs, utilities, miscellaneous expenses,
}; and net income.

int main() { 3. Main Function:


fstream indata;
ofstream outdata; - Declares file streams `indata` and `outdata`.

indata.open("income.dat", ios::out | - Opens the file "income.dat" for writing binary


ios::binary); // open file as binary output. data (`ios::out | ios::binary`) and the file
outdata.open("student.out"); // "student.out" for writing text data.
output file that we will write student information
to. - Sets the output formatting for the text file
outdata << left << fixed << setprecision(2); (`left`, `fixed`, `setprecision`).
// left indicates left justified for fields
- Prompts the user to input financial information:
budget person; // defines person to be a record
cout << "Enter the following information" << - Reads the person's name (using `cin.getline()`
endl; to handle spaces).
cout << "Person's name: ";
cin.getline(person.name, NAMESIZE); - Reads the person's income and various
cout << "Income: "; expenses (rent, food, utilities, miscellaneous)
cin >> person.income; using standard input (`cin`).
cout << "Rent: ";
cin >> person.rent; - Calculates the net income (income - expenses).
cout << "Food: ";
cin >> person.food; - Writes the `person` structure to the binary file
cout << "Utilities: "; "income.dat" using `indata.write()`, converting the
cin >> person.utilities; structure to a character array using
cout << "Miscellaneous: "; `reinterpret_cast<char*>()`.
cin >> person.miscell;
- Closes the binary file.
// find the net field
person.net = person.income - (person.rent + - Reopens "income.dat" for reading binary data
person.food + person.utilities + person.miscell); (`ios::in | ios::binary`).
- Reads the `person` structure from the file using
// write this record to the file `indata.read()`.
indata.write(reinterpret_cast<char*>(&person),
sizeof(person)); - Writes the financial information to the output
indata.close(); file "student.out" with appropriate formatting
using `setw()`.
// REOPEN THE "income.dat" FILE, NOW AS
AN INPUT FILE 4. End of Program: Returns 0 to indicate
indata.open("income.dat", ios::in | ios::binary); successful execution.

// READ THE RECORD FROM FILE AND This program essentially acts as a data entry tool
PLACE IT IN THE person RECORD for recording financial information, stores this
indata.read(reinterpret_cast<char*>(&person), data in a binary file,
sizeof(person));
retrieves it, and then formats and outputs it to a
// write information to output file text file for further analysis or reporting.
outdata << setw(20) << "Name" << setw(10)
<< "Income" << setw(10) << "Rent"
<< setw(10) << "Food" << setw(15) <<
"Utilities" << setw(15)
<< "Miscellaneous" << setw(10) << "Net
Money" << endl << endl;
outdata << setw(20) << person.name <<
setw(10) << person.income << setw(10) <<
person.rent
<< setw(10) << person.food << setw(15)
<< person.utilities << setw(15)
<< person.miscell << setw(10) <<
person.net << endl;

return 0;
}

Output:-
Task # 3

Program:- Description:-
# Function to read records from the keyboard Sure, here's a description of the provided code:
def read_records():
records = [] 1. Reading Records from Keyboard
while True: (`read_records`):
first_name = input("Person's First Name: ") - This function prompts the user to input
last_name = input("Person's Last Name: ") information for each field of a record.
street = input("Street: ") - It collects this information and appends it to a
city = input("City: ") list of records.
state = input("State: ") - The function continues to prompt the user until
zip_code = input("Zip: ") they indicate they don't want to input more data.
records.append((first_name.ljust(15),
last_name.ljust(15), street.ljust(30), city.ljust(20), 2. Writing Records to Binary File
state.ljust(5), zip_code)) (`write_to_binary`):
more_data = input("Enter Y if you would like - This function takes a list of records as input
to input more data: ") and writes each record to a binary file.
if more_data.upper() != 'Y': - Each field of the record is converted to bytes
break and written to the file.
return records - For the zip code, it's converted to a 32-bit
integer before being written to the file.
# Function to write records to a binary file
def write_to_binary(records): 3. Reading Records from Binary File
with open("records.bin", "wb") as f: (`read_from_binary`):
for record in records: - This function reads records from a binary file.
for field in record[:-1]: # Write all fields - It calculates the number of records in the file
except the last one (zip code) by dividing the total file size by the size of each
f.write(field.encode()) record.
f.write(int(record[-1]).to_bytes(4, - Then, it iterates over each record in the file.
byteorder='big')) # Write the zip code as a 32-bit - It seeks to the appropriate position from the
integer end of the file to read each record.
- Each field of the record is extracted from the
# Function to read records from a binary file bytes read, and the zip code is converted back
def read_from_binary(): from bytes to an integer.
records = []
with open("records.bin", "rb") as f: 4. Writing Records to Text File (`write_to_text`):
file_size = f.seek(0, 2) # Get the size of the - This function takes a list of records as input
file and writes them to a text file.
record_size = 86 # Size of each record - It formats each record to align the fields
num_records = file_size // record_size # properly in a tabular format and writes them to the
Calculate the number of records file.
for i in range(num_records):
f.seek(-((i + 1) * record_size), 2) # Move 5. Main Program:
the pointer to the beginning of the i-th record from - In the main program, it first reads records from
the end of the file the keyboard using `read_records`.
data = f.read(record_size) # Read the i-th - Then it writes these records to a binary file
record using `write_to_binary`.
first_name = data[:15].decode().rstrip() - After that, it reads the records back from the
last_name = data[15:30].decode().rstrip() binary file using `read_from_binary`.
street = data[30:60].decode().rstrip() - Finally, it writes these records to a text file
city = data[60:80].decode().rstrip() using `write_to_text`.
state = data[80:85].decode().rstrip()
zip_code = int.from_bytes(data[85:], 'big') Overall, this code allows the user to input records
# Read zip code as a 32-bit integer from the keyboard, stores them in a binary file,
records.append((first_name, last_name, retrieves them from the binary file, and then
street, city, state, zip_code)) writes them to a text file in a formatted manner.
return records

# Function to write records to a text file


def write_to_text(records):
with open("records.txt", "w") as f:
f.write("First Name Last Name Street
City State Zip Code\n")
for record in records:
f.write("{:<15} {:<15} {:<30} {:<20}
{:<5} {:<8}\n".format(*record))

# Main program
if __name__ == "__main__":
records = read_records()
write_to_binary(records)
records = read_from_binary()
write_to_text(records)
print("Data written to records.txt")
Conclusion:-
The provided code implements a program that manages records of individuals, allowing users to input
data from the keyboard, store it in a binary file, read it back, and then write it to a text file. The input
process is structured, prompting users for each field of a record, ensuring consistent formatting. Records
are stored in a binary file using fixed-size fields, with the zip code converted to a 32-bit integer for
storage efficiency. Reading from the binary file is implemented to retrieve records from the end,
calculating the file's size and record size to determine the correct position. The retrieved records are then
processed and written to a text file, formatted in a tabular manner for readability. Overall, the program
provides a robust way to manage and manipulate records, offering flexibility in data input, efficient
storage in binary format, and clear presentation in the output text file.

You might also like