-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileInOutExceptionDEMO.cpp
More file actions
84 lines (69 loc) · 2.38 KB
/
Copy pathFileInOutExceptionDEMO.cpp
File metadata and controls
84 lines (69 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//************************************************************************
// Author: Rolando Carreon
// Date: apr 3 2025
// Language: C++
// Assignment: Demo
// Description: write to and read from a fule, using exception handling
// to manage files not being opened
//************************************************************************
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
// declare local variables
string studentFirstName;
string studentLastName;
double studentGrade = 0.0;
double totalGrades = 0.0;
int countOfRecords = 0;
// try to create the file
// try to see if u have permissions to open and edit
try
{
// create a ouput fule stream to file
ofstream studentFile( "student.txt" );
// add data to the file
studentFile << "Sam Read 92.3\n";
studentFile << "Fred Flinstone 89.2\n";
studentFile << "Bart Simpson 72.5\n";
studentFile << "Sally Smith 98.3";
// close the file
studentFile.close();
}
catch (...)
{
cout << "Yikes = something happened - the file was not writtin.\n";
}
// try to open the file and read the contents
try
{
// crate a file input stream and read the data
ifstream studentFile("student.txt");
// read the data one line at a time
//while ( studentFile )
// use this while instead so it stops loop at the end of the file
while ( !studentFile.eof() )
{
// read a line of data
studentFile >> studentFirstName >> studentLastName
>> studentGrade;
// display the student data
cout << "Student: " << studentLastName << ", "
<< studentFirstName << "\tGrade: " << studentGrade << endl;
// add studentGrade to the totalGrades, increment the count
totalGrades += studentGrade;
countOfRecords++;
}
// close the file
studentFile.close();
//calculate and display the average grade
cout << "Average of Class is: "
<< totalGrades / countOfRecords << endl;
}
catch (...)
{
cout << "Yikes - something happened - the file was not opened.\n";
}
return 0;
}