-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathch14_exercise.ixx
570 lines (482 loc) · 14.5 KB
/
ch14_exercise.ixx
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
export module ch14_exercise;
import std;
export namespace ch14_exercise {
namespace ex2 {
using namespace std;
void changeNumberForID(string_view filename, int id, string_view newNumber)
{
fstream ioData{ filename.data() };
if (ioData.fail()) {
// We failed to open the file: throw an exception.
throw runtime_error{format("failed to open the file {}", filename.data())};
}
// Loop until the end of file
while (ioData) {
// Read the next ID.
int idRead;
ioData >> idRead;
if (!ioData)
break;
// Check to see if the current record is the one being changed.
if (idRead == id) {
// Seek the write position to the current read position.
ioData.seekp(ioData.tellg());
if (ioData.fail()) {
throw runtime_error{ "seekp and/or tellg failed" };
}
// Output a space, then the new number.
ioData << " " << newNumber;
if (ioData.fail()) {
throw runtime_error{ "failed to write to the output stream with space and number" };
}
break;
}
// Read the current number to advance the stream.
string number;
ioData >> number;
if (ioData.fail()) {
throw runtime_error{ "failed to read the current number to advance the stream" };
}
}
}
void test() {
std::string filePath = "D:\\cppliblearn\\professionalcppbook\\profcppbook\\data.txt"; // or use forward slashes
try {
changeNumberForID(filePath, 263, "415-555-3333");
}
catch (const exception& e) {
cerr << format("Caught exception is: {}", e.what()) << endl;
}
}
}
namespace ex3 {
using namespace std;
class Person
{
public:
// Two-parameter constructor automatically creates initials and
// delegates the work to the three-parameter constructor.
Person(std::string firstName, std::string lastName)
: Person{ std::move(firstName), std::move(lastName),
std::format("{}{}", firstName[0], lastName[0]) }
{
}
Person() = default;
Person(std::string firstName, std::string lastName, std::string initials)
: m_firstName{ std::move(firstName) }
, m_lastName{ std::move(lastName) }
, m_initials{ std::move(initials) }
{
}
const std::string& getFirstName() const { return m_firstName; }
void setFirstName(std::string firstName) { m_firstName = std::move(firstName); }
const std::string& getLastName() const { return m_lastName; }
void setLastName(std::string lastName) { m_lastName = std::move(lastName); }
const std::string& getInitials() const { return m_initials; }
void setInitials(std::string initials) { m_initials = std::move(initials); }
void output(std::ostream& output) const
{
output << std::format("{} {} ({})",
getFirstName(), getLastName(), getInitials()) << std::endl;
}
// Only this single line of code is needed to add support
// for all six comparison operators.
[[nodiscard]] auto operator<=>(const Person&) const = default;
private:
std::string m_firstName;
std::string m_lastName;
std::string m_initials;
};
class Database
{
public:
// Adds the given person to the database.
void add(Person person);
// Removes all persons from the database.
void clear();
// Saves all persons in the database to the given file.
void save(std::string_view filename) const;
// Loads all persons from the given file and stores them in the database.
void load(std::string_view filename);
// Outputs all persons to the given stream.
void outputAll(std::ostream& output) const;
private:
std::vector<Person> m_persons;
};
void Database::add(Person person)
{
m_persons.push_back(move(person));
}
void Database::clear()
{
m_persons.clear();
}
void Database::save(string_view filename) const
{
ofstream outFile{ filename.data(), ios_base::trunc };
if (!outFile) {
// We failed to open the file: throw an exception.
throw runtime_error{ format("failed to open the file {} for saving.", filename.data()) };
}
for (const auto& person : m_persons) {
// We need to support spaces in names.
// So, to be able to read back names later in load(),
// we simply quote all parts of the name.
outFile << quoted(person.getFirstName())
<< quoted(person.getLastName())
<< quoted(person.getInitials()) << endl;
if (!outFile) {
// We failed to open the file: throw an exception.
throw runtime_error{ format("failed to write {}, {}, {} in the file {} for saving.",
person.getFirstName(),
person.getLastName(),
person.getInitials(),
filename.data())
};
}
}
}
void Database::load(string_view filename)
{
ifstream inFile{ filename.data() };
if (!inFile) {
// We failed to open the file: throw an exception.
throw runtime_error{ format("failed to open the file {} for loading.", filename.data()) };
}
while (inFile) {
// Read line by line, so we can skip empty lines.
// The last line in the file is empty, for example.
string line;
getline(inFile, line);
if (!inFile && !inFile.eof()) {
throw runtime_error{ format("failed to read line from file.") };
}
if (line.empty()) { // Skip empty lines
continue;
}
// Make a string stream and parse it.
istringstream inLine{ line };
string firstName, lastName, initials;
inLine >> quoted(firstName) >> quoted(lastName) >> quoted(initials);
if (inLine.bad()) {
cerr << "Error reading person. Ignoring." << endl;
continue;
}
// Create a person and add it to the database.
m_persons.push_back(Person{ move(firstName), move(lastName), move(initials) });
}
}
void Database::outputAll(ostream& output) const
{
for (const auto& person : m_persons) {
person.output(output);
}
}
void test() {
try {
// Fill a database.
Database db;
db.add(Person{ "John", "Doe" });
db.add(Person{ "Marc", "Gregoire", "Mg" });
db.add(Person{ "Peter", "Van Weert", "PVW" });
// Output all persons in the database to standard output.
cout << "Initial database contents:" << endl;
db.outputAll(cout);
// Save the database to a file.
db.save("person_ch14.db");
// Clear the database.
db.clear();
cout << "\nDatabase contents after clearing:" << endl;
db.outputAll(cout);
// Load database from file.
cout << "\nLoading database from file..." << endl;
db.load("person_ch14.db");
cout << "\nDatabase contents after loading from file:" << endl;
db.outputAll(cout);
}
catch (const exception& e) {
cerr << format("Caught exception in original test code: {}", e.what()) << endl;
}
try {
// Fill a database.
Database db;
db.add(Person{ "John", "Doe" });
db.add(Person{ "Marc", "Gregoire", "Mg" });
db.add(Person{ "Peter", "Van Weert", "PVW" });
// Output all persons in the database to standard output.
cout << "Initial database contents:" << endl;
db.outputAll(cout);
// Save the database to a read only file.
db.save("read_only.db");
// Clear the database.
db.clear();
cout << "\nDatabase contents after clearing:" << endl;
db.outputAll(cout);
// Load database from file.
cout << "\nLoading database from file..." << endl;
db.load("person_ch14.db");
cout << "\nDatabase contents after loading from file:" << endl;
db.outputAll(cout);
}
catch (const exception& e) {
cerr << format("Caught exception in problematic test code for writing: {}", e.what()) << endl;
}
try {
// Fill a database.
Database db;
// Load database from file.
cout << "\nLoading database from file..." << endl;
db.load("write_only.db");
cout << "\nDatabase contents after loading from file:" << endl;
db.outputAll(cout);
}
catch (const exception& e) {
cerr << format("Caught exception in problematic test code for reading: {}", e.what()) << endl;
}
}
}
namespace ex4 {
using namespace std;
class SpreadsheetCell
{
public:
SpreadsheetCell() = default;
SpreadsheetCell(double initialValue);
SpreadsheetCell(std::string_view initialValue);
void setValue(double value);
double getValue() const;
void setString(std::string_view value);
std::string getString() const;
private:
std::string doubleToString(double value) const;
double stringToDouble(std::string_view value) const;
double m_value{ 0 };
};
class Spreadsheet
{
public:
Spreadsheet(size_t width, size_t height);
Spreadsheet(const Spreadsheet& src);
Spreadsheet(Spreadsheet&& src) noexcept; // Move constructor
~Spreadsheet();
Spreadsheet& operator=(const Spreadsheet& rhs);
Spreadsheet& operator=(Spreadsheet&& rhs) noexcept; // Move assignment
void setCellAt(size_t x, size_t y, const SpreadsheetCell& cell);
SpreadsheetCell& getCellAt(size_t x, size_t y);
void swap(Spreadsheet& other) noexcept;
static const size_t m_maxwidth{ 100 };
static const size_t m_maxheight{ 100 };
private:
void cleanup() noexcept;
void verifyCoordinate(size_t x, size_t y) const;
size_t m_width{ 0 };
size_t m_height{ 0 };
SpreadsheetCell** m_cells{ nullptr };
};
void swap(Spreadsheet& first, Spreadsheet& second) noexcept;
class InvalidCoordinate : public exception
{
public:
InvalidCoordinate(size_t width, size_t height, size_t maxwidth, size_t maxheight) :
m_width{ width },
m_height{ height },
m_maxwidth{ maxwidth },
m_maxheight{ maxheight }
{
m_message = format("Allowed range:[0-{})*[0-{}), but received {}*{}",
m_maxwidth, m_maxheight, m_width, m_height);
}
const char* what() const noexcept override { return m_message.c_str(); }
private:
size_t m_width{ 0 };
size_t m_height{ 0 };
size_t m_maxwidth{ 0 };
size_t m_maxheight{ 0 };
string m_message;
};
SpreadsheetCell::SpreadsheetCell(double initialValue)
: m_value{ initialValue }
{
}
SpreadsheetCell::SpreadsheetCell(string_view initialValue)
: m_value{ stringToDouble(initialValue) }
{
}
void SpreadsheetCell::setValue(double value)
{
m_value = value;
}
double SpreadsheetCell::getValue() const
{
return m_value;
}
void SpreadsheetCell::setString(string_view value)
{
m_value = stringToDouble(value);
}
string SpreadsheetCell::getString() const
{
return doubleToString(m_value);
}
string SpreadsheetCell::doubleToString(double value) const
{
return to_string(value);
}
double SpreadsheetCell::stringToDouble(string_view value) const
{
double number{ 0 };
from_chars(value.data(), value.data() + value.size(), number);
return number;
}
Spreadsheet::Spreadsheet(size_t width, size_t height)
{
cout << "Normal constructor" << endl;
if (width > m_maxwidth || height > m_maxheight) {
throw InvalidCoordinate{ width, height, m_maxwidth, m_maxheight };
}
m_cells = new SpreadsheetCell * [width] {};
//only set width and height only allocation succeed.
m_width = width;
m_height = height;
try {
for (size_t i{ 0 }; i < m_width; i++) {
m_cells[i] = new SpreadsheetCell[m_height];
}
}
catch (...) {
cleanup();
throw_with_nested(bad_alloc{});
}
}
Spreadsheet::~Spreadsheet()
{
try {
cleanup();
}
catch (const exception& e) {
cerr << format("Caught exception in Spreadsheet::~Spreadsheet(): {}, delete failed", e.what()) << endl;
}
}
void Spreadsheet::cleanup() noexcept
{
for (size_t i{ 0 }; i < m_width; i++) {
delete[] m_cells[i];
}
delete[] m_cells;
m_cells = nullptr;
m_width = m_height = 0;
}
Spreadsheet::Spreadsheet(const Spreadsheet& src)
: Spreadsheet{ src.m_width, src.m_height }
{
cout << "Copy constructor" << endl;
// The ctor-initializer of this constructor delegates first to the
// non-copy constructor to allocate the proper amount of memory.
// The next step is to copy the data.
for (size_t i{ 0 }; i < m_width; i++) {
for (size_t j{ 0 }; j < m_height; j++) {
m_cells[i][j] = src.m_cells[i][j];
}
}
}
void Spreadsheet::verifyCoordinate(size_t x, size_t y) const
{
if (x >= m_width || y >= m_height) {
throw InvalidCoordinate{ x,y,m_width,m_height };
}
}
void Spreadsheet::setCellAt(size_t x, size_t y, const SpreadsheetCell& cell)
{
verifyCoordinate(x, y);
m_cells[x][y] = cell;
}
SpreadsheetCell& Spreadsheet::getCellAt(size_t x, size_t y)
{
verifyCoordinate(x, y);
return m_cells[x][y];
}
void Spreadsheet::swap(Spreadsheet& other) noexcept
{
std::swap(m_width, other.m_width);
std::swap(m_height, other.m_height);
std::swap(m_cells, other.m_cells);
}
void swap(Spreadsheet& first, Spreadsheet& second) noexcept
{
first.swap(second);
}
Spreadsheet& Spreadsheet::operator=(const Spreadsheet& rhs)
{
cout << "Copy assignment operator" << endl;
// Copy-and-swap idiom
Spreadsheet temp{ rhs }; // Do all the work in a temporary instance
swap(temp); // Commit the work with only non-throwing operations
return *this;
}
// Move constructor
Spreadsheet::Spreadsheet(Spreadsheet&& src) noexcept
{
cout << "Move constructor" << endl;
ex4::swap(*this, src);
}
// Move assignment operator
Spreadsheet& Spreadsheet::operator=(Spreadsheet&& rhs) noexcept
{
cout << "Move assignment operator" << endl;
ex4::swap(*this, rhs);
return *this;
}
Spreadsheet createObject()
{
return Spreadsheet{ 3, 2 };
}
void test() {
vector<Spreadsheet> vec;
for (size_t i{ 0 }; i < 2; ++i) {
cout << "Iteration " << i << endl;
vec.push_back(Spreadsheet{ 100, 100 });
cout << endl;
}
Spreadsheet s{ 2, 3 };
s = createObject();
Spreadsheet s2{ 5, 6 };
s2 = s;
try {
Spreadsheet s{ 2, 3 };
s.getCellAt(1, 2);
s.getCellAt(2, 3);
}
catch (const exception& e) {
cerr << format("Caught exception for getCellAt: {}", e.what()) << endl;
}
try {
Spreadsheet s{ 50, 30 };
s.setCellAt(25, 15, SpreadsheetCell{ 2 });
s.setCellAt(53, 33, SpreadsheetCell{ 6 });
}
catch (const exception& e) {
cerr << format("Caught exception for setCellAt: {}", e.what()) << endl;
}
try {
Spreadsheet s{ 100, 256 };
}
catch (const exception& caughtException) {
cerr << caughtException.what() << endl;
}
try {
Spreadsheet s{ 49, 49 };
auto& cell = s.getCellAt(55, 55);
}
catch (const exception& caughtException) {
cerr << caughtException.what() << endl;
}
try {
Spreadsheet s{ 49, 49 };
s.setCellAt(55, 55, SpreadsheetCell{ 1.2 });
}
catch (const exception& caughtException) {
cerr << caughtException.what() << endl;
}
}
}
}