-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathExercise 14.4
85 lines (58 loc) · 2.37 KB
/
Exercise 14.4
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
1. (Practice) List two conditions that cause a fail condition when a file is opened for input.
If the file does not exist and can't be created.
2. (Practice) List two conditions that cause a fail condition when a file is opened for output.
If a file does not exist and can not be overwritten.
3. (Practice) If an existing file is opened for output in write mode, what happens to the data
currently in the file?
The data currently in the file is deleted and overwritten.
4. (Modify) Modify Program 14.15 to use an identifier of your choice, in place of the letter e, for
the catch block’s exception parameter name.
//Done!!
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cstdlib> // needed for exit()
#include <string>
using namespace std;
int main()
{
string filename = "prices.dat"; // put the filename up front
string descrip;
double price;
ifstream inFile;
try // tries to open the file, read it, and display file's data
{
inFile.open(filename.c_str());
if (inFile.fail()) throw filename; // exception being checked
// read and display the file's contents
inFile >> descrip >> price;
while (inFile.good()) // check next character
{
cout << descrip << ' ' << price << endl;
inFile >> descrip >> price;
}
inFile.close();
return 0;
}
catch (string awesome)
{
cout << "\nThe file " << awesome << " was not successfully opened."
<< "\n Please check that the file currently exists."
<< endl;
exit(1);
}
}
5. (Practice) Enter and run Program 14.16.
//Done!!
6. (Debug) Determine why the two unnested try blocks in Program 14.16 cause no problems
in compilation or execution. (Hint : Place the declaration for the filename in the first try block
and compile the program.)
7. (Debug) a. If the nested try blocks in the preceding Point of Information are separated into
unnested blocks, the program won’t compile. Determine why this is so.
b. What additional changes have to be made to the program in Exercise 7a to allow it to be
written with unnested blocks? (Hint : See Exercise 6.)
8. (Program) Enter the data for the info.txt file in Figure 14.11 or download it from this
book’s Web site (see this book’s introduction for the URL). Then enter and run Program 14.17
and verify that the backup file was written.
9. (Modify) Modify Program 14.17 to use a getline() method in place of the get() method
currently in the program.