0% found this document useful (0 votes)
58 views9 pages

Practical 11 Files

The document provides code examples and explanations for 4 programming exercises involving file input/output in C++. The first exercise calculates the product of numbers read from a file. The second reads numbers from a file into an array and displays them in reverse order. The third takes words from the user and writes them to a file with spaces between each letter. The fourth reads student data from a file into an array of structures, calculates averages, and writes a report to an output file.

Uploaded by

Jing Ze
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)
58 views9 pages

Practical 11 Files

The document provides code examples and explanations for 4 programming exercises involving file input/output in C++. The first exercise calculates the product of numbers read from a file. The second reads numbers from a file into an array and displays them in reverse order. The third takes words from the user and writes them to a file with spaces between each letter. The fourth reads student data from a file into an array of structures, calculates averages, and writes a report to an output file.

Uploaded by

Jing Ze
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/ 9

UECS1643 Fundamentals Of Programming

Practical 11 – refer to Topics 20 and 21

Part A (Understanding Concepts)

1. Open notepad, type the following content and save it as “inputstring.txt” to the same folder where your
source file is placed.

An apple a day keeps the doctor away.


A stitch in time saves nine.
More haste less speed.

Copy and paste the following code as the source file and run it.

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main()
{
char line[51];
ifstream inFile("inputstring.txt");
ofstream outFile("outputstring.txt");

if (!inFile || !outFile)
{
if(!inFile)
cout << "Error opening input file\n";

if (!outFile)
cout << "Error opening output file\n";
}
else
{
inFile.getline(line, 51);
while(inFile)
{
int len = strlen(line);
for (int i = 0; i < len; i++)
line[i] = toupper(line[i]);

outFile << line << endl;

inFile.getline(line, 51);
}

inFile.close();
outFile.close();
}

return 0;
}

1
UECS1643 Fundamentals Of Programming

(a) Where is the output file “outputstring.txt” It is stored to the same folder where the source file is
stored to? placed.

(b) Modify the highlighted code so that the output ofstream outFile(“e:outputstring.txt”);
file is saved to your thumb drive instead.
Assuming the thumb drive at drive e.

(c) What is stored in the output file?

(d) Modify the code inside the while loop so that while (inFile)
{
you will get the following output file content (the int len = strlen(line);
case of the letters is inverted and the punctuation for (int i = 0; i < len; i++)
marks are discarded and replaced by whitespaces): if (islower(line[i]))
line[i] = toupper(line[i]);
else if (isupper(line[i]))
aN APPLE A DAY KEEPS THE DOCTOR AWAY line[i] = tolower(line[i]);
a STITCH IN TIME SAVES NINE else if (ispunct(line[i]))
line[i] = ' ';
mORE HASTE LESS SPEED
outFile << line << endl;

inFile.getline(line, 51);
}

*** need to add library file <cctype>

2. Given the following input and output files together with the declarations:

ifstream inFile;
ofstream outFile;
int number1, number2, result;

(a) Write statements to open a file named ifstream inFile(“mydata.txt”,ios::in);


“mydata.txt” for reading and associate it ofstream outFile(“myreport.txt”,ios::out);
with file stream inFile and to open a file
named myreport.txt” for writing and if(!inFile)
associate it with file stream outFile.
{
Check for any errors when opening the
files. cout << “Error opening input file\n”;

2
UECS1643 Fundamentals Of Programming

exit(100);
}

If(!outFile)
{
cout << “Error opening input file\n”;
exit(100);
}

(b) Write statements to read the two numbers inFile>> number1 >> number2;
from “mydata.txt” into 2 variables called result = number1 + number2;
number1 and number2, compute their sum outFile << “Result is” << result;
and store into a variable called result,
and write the result to the file
“myreport.txt”.

(c) Write statements to close the two files. inFile.close();


outFile.close();

Part B (Programming Exercises)


1. Write a program to read a set of numbers from a file (“numbers.txt”), compute and display the product of the
numbers on the screen.
#include<iostream>
#include<fstream>
using namespace std;

int main(void)
{
int number, product= 1;

ifstream inFile("numbers.txt", ios::in);

if (!inFile)
cout << "Error opening inout file\n";
else
{
inFile >> number;
while (inFile)
{
product *= number;
inFile >> number;
}
cout << "Product of the numbers is " << product << endl;
inFile.close();
}
return 0;
}

3
UECS1643 Fundamentals Of Programming

2. Write a program to read a set of numbers from a file, store them in an array, and display the numbers in reverse
order. Assume there are no more than 30 numbers in the file.
#include<iostream>
#include<fstream>
using namespace std;

int main(void)
{
int numbers[30], count = 0;
ifstream inFile("numbers.txt");

if (!inFile)
cout << "Error opening input file\n";
else
{
inFile >> numbers[count];
while (inFile)
{
inFile >> numbers[++count];
}
cout << "The numbers in reverse are: \n";
for (int i = count - 1; i >= 0;i--)
{
cout << numbers[i] << " ";
}
cout << endl;
inFile.close();
}
return 0;
}

4
UECS1643 Fundamentals Of Programming

3. Write a program to input a set of words from the user and write the words to a file with spaces added in
between the letters. Assume the longest word is 20 characters long. A sample input and output is as follows:
Input/Output using keyboard/screen Output file contents
Enter a word: Apple Apple
Enter a word: Ball Ball
Enter a word: Chair Chair
Enter a word: Dog Dog
Enter a word: Elephant Elephant
Enter a word: ^Z
#include<iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main(void)
{
char word[21];
ofstream outFile("PartBQ3.txt");

if (!outFile)
cout << "Error opening output file\n";
else
{
do
{
cout << "Enter a word: ";
cin >> word;
for (int i = 0; i < strlen(word);i++)
outFile << word[i] << " ";
outFile << endl;
} while (cin);
outFile.close();
}
return 0;
}

5
UECS1643 Fundamentals Of Programming

4. Write a program to read an input file containing student data. Each line of text in the file contains a student’s
registration number and 3 test scores. The program computes the average score.

Use a structure to represent a student. The structure has 5 members to store the registration number (string), 3
test scores (array of floats), and average score (float). The program should be able to handle a maximum of 50
students using an array of structures. The program produces an output file with a report showing, for each
student, the registration number, 3 tests scores, and the average score.

A sample of the input and output file is as follows:


Input file contents Output file contents
UA1001 82.0 91.0 76.0 Reg. No. Test1 Test2 Test3 Average
UA1002 77.0 54.0 61.5 UA1001 82.0 91.0 76.0 xx.x
UA1003 65.5 63.0 62.0 UA1002 77.0 54.0 61.5 xx.x
UA1003 65.5 63.0 62.0 xx.x

#include<iostream>
#include<fstream>
#include<cstring>
#include <iomanip>
using namespace std;

typedef struct
{
char reg_no[7];
float scores[3];
float average;
}STUDENT_TYPE;

int main(void)
{
STUDENT_TYPE students[50];
int index = 0;
float total;
ifstream inFile("inputPartBQ4.txt");
ofstream outFile("outputPartBQ4.txt");

if (!inFile || !outFile)
{
if (!inFile)
cout << "Error opening input file\n";
if (!outFile)
cout << "Error opening input file\n";
}
else
{
outFile << "Reg. No. \t Test1\t Test2\t Test3\t Average\n";
inFile >> students[index].reg_no;
while (inFile)
{
//read record and calculate average
total = 0.0;
for (int i = 0;i < 3; i++)
{
inFile >> students[index].scores[i];
total += students[index].scores[i];
}
students[index].average = total / 3;

//write report

6
UECS1643 Fundamentals Of Programming

outFile << fixed << setprecision(1);


outFile << students[index].reg_no<<"\t\t";
for (int i = 0; i < 3; i++)
outFile << setw(6) << students[index].scores[i] << "\t";
outFile << setw(8) << students[index].average << endl;

//read next reg no


inFile >> students[++index].reg_no;
}
inFile.close();
outFile.close();
}
return 0;
}

Part C (Self-Review / Revision)


1. What must be done before a file can be used for reading or writing? after we have finished using it?
The file must be opened before we use it. It must be closed after we have finished using it.
2. What are the different file modes that can be used when opening a file?
ios::in – reading, ios::out- writing, ios::app-appending

Part D (Practice Exercises)

1. Write and test a program that reads product details from a file and stores the information in an array of
structures. The program then prints a menu to allow the user to do any of the following:
1. List all products
2. Search the price of a product
3. Update the price of a product
4. Exit
If the user chooses to exit, the program will write the updated data in the array of structures to the file.

Product information includes product number, description and price.


#include<iostream>
#include<iomanip>
#include<fstream>
#include<cstring>
using namespace std;

typedef struct
{
char number[6];
char desc[31];
double price;
} PRODUCT_TYPE;

void list(PRODUCT_TYPE prod[], int rows);


void showPrice(PRODUCT_TYPE prod[], int rows);
void updatePrice(PRODUCT_TYPE prod[], int rows);
int searchProduct(PRODUCT_TYPE prod[], int rows);

int main()
{
PRODUCT_TYPE products[50];
int index = 0, choice;
ifstream inFile("product.txt");

if (!inFile)
cout << "Error opening input file\n";
else

7
UECS1643 Fundamentals Of Programming

{
inFile >> products[index].number;
while (inFile)
{
inFile.ignore();
inFile.getline(products[index].desc, 31);
inFile >> products[index].price;

// read next number


inFile >> products[++index].number;
}
inFile.close();

// menu starts
do
{
cout << "\nDo you want to:\n";
cout << "1. List all products\n";
cout << "2. Display the price for a product\n";
cout << "3. Update the price for a product\n";
cout << "4. Exit\n";
cout << "Enter choice: ";
cin >> choice;

switch (choice)
{
case 1: list(products, index);
break;
case 2: showPrice(products, index);
break;
case 3: updatePrice(products, index);
break;
case 4: break;
default: cout << "Invalid choice\n";
}
} while (choice != 4);

ofstream outFile("product.txt");
if (!outFile)
cout << "Error opening output file, records are not updated.\n";
else
{
for (int i = 0; i< index; i++)
{
outFile << products[i].number << endl;
outFile << products[i].desc << endl;
outFile << products[i].price << endl;
}
outFile.close();

}
}
return 0;
}

void list(PRODUCT_TYPE prod[], int rows)


{
cout << fixed << setprecision(2);
for (int i = 0; i<rows; i++)
cout << prod[i].number << "\t" << prod[i].desc << "\t"
<< setw(8) << prod[i].price << endl;
return;

8
UECS1643 Fundamentals Of Programming

int searchProduct(PRODUCT_TYPE prod[], int rows)


{
int i = 0;
bool found = false;
char number[6];

cout << "Enter product number to search: ";


cin >> number;

while (i<rows&& !found)


{
if (strcmp(number, prod[i].number) == 0)
found = true;
else
i++;
}
if (found)
return i;
else
return -1;
}

void showPrice(PRODUCT_TYPE prod[], int rows)


{
int pos = searchProduct(prod, rows);
if (pos != -1)
cout << "Current price is " << fixed << setprecision(2) << prod[pos].price
<< endl;
else
cout << "Product not found\n";

return;
}

void updatePrice(PRODUCT_TYPE prod[], int rows)


{
double newPrice;

int pos = searchProduct(prod, rows);


if (pos != -1)
{
cout << "Current price is " << fixed << setprecision(2) << prod[pos].price;
cout << "\nEnter new price: ";
cin >> newPrice;
prod[pos].price = newPrice;
cout << "Price updated!\n";
}
else
cout << "Product not found\n";

return;
}

You might also like