1. Goals
Combine Foundation topics into a program you can use and debug.
Add, find and sort books in a
vectorwhile keeping IDs unique.Separate declarations, data handling and user interaction into multiple files.
Save/load files, report failures and preserve current data on a failed load.
2. Prerequisites
You know classes, reference parameters, lifetimes, RAII, string,
vector, iterators, sorting, headers/linking and file I/O.
This project uses standard value types. It does not need manual allocation
or a new inheritance/template abstraction just to use every recently learned tool.
3. Explanation
The program accepts one command per line:
add 1 C++ Basics: add ID1with titleC++ Basics.find 1: look up an ID.list: print the current order;sort: order books by title.save: overwrite the practice filebooks-demo.txtin the working directory.load: replace current books with that file if all its contents are valid.quit: exit. Normal end of input also exits, without automatically saving.
An ID is a positive value representable by int, containing only digits
0–9, and must be unique. 0, -1, +1, 1abc and overflowing
numbers are rejected. Leading zeroes are accepted: 01 duplicates ID 1.
Titles must be nonempty, with no leading/trailing whitespace or newline
characters. Internal whitespace is preserved. Command/file parsing skips
separator whitespace before the ID and before the title. There is no
quoting syntax: everything after the ID's separator is the title.
Library owns a vector<Book>; each Book owns its title string.
add validates before insertion, so rejecting a duplicate does not change
the old book. Callers only receive read-only access through books();
they cannot edit IDs directly and break the invariant. Copying a
Library produces independent data through its value-type members.
find returns a borrowed pointer to an element, or nullptr; ownership
is not transferred. Never delete it. add may reallocate, sort may
change which book occupies a position, and successful load replaces
all elements. Find the ID again after mutations, and never use borrowed
elements after their owning Library dies. The reference to the vector
object from books() still refers to that member while its Library
lives; pointers/references to its elements have separate validity rules.
See vector insertion rules.
Finding an ID takes up to n comparisons. Adding also searches for a
duplicate, so its total cost is more than push_back. Loading n
books checks duplicates repeatedly and can require comparisons proportional
to n²; this is acceptable for the small exercise dataset. Sorting uses
about n log n title comparisons, each also depending on string lengths.
Equal titles are ordered by ID. String ordering is case-sensitive and is
not human-language alphabetical collation.
The file format is one book per line: id title. Blank lines are invalid;
an empty file means an empty library. A final newline is optional.
parseBookLine removes one trailing \r left over from a Windows
\r\n line ending, but rejects newline characters within a title.
save uses text-stream line endings on the current system.
load reads into a temporary library. It swaps data only after every
record, uniqueness check and stream-state check succeeds. A failed load
preserves the current list; success replaces rather than appends.
save checks writing/flushing; saveFile also closes and checks the
result. RAII closes file resources on early return as well.
Stream functions assume default exception settings. If the caller enables
exceptions(), stream errors can throw; allocation failures are not
converted to false either.
Saving retains the previous lesson's limits: opening with trunc discards
old contents, and a later error can leave a partial file. It is not an
atomic save, backup mechanism or guarantee against power loss. This is a
single-process exercise for small datasets. Only save creates/writes a
file; exiting does not save automatically.
The three files have separate roles: library.hpp declares types/functions,
library.cpp implements data rules and persistence, and main.cpp reads
commands and prints responses. Do not #include a .cpp file; compile
both source files and link them.
4. Runnable example
Create all three files in a new practice directory. main.cpp alone
is insufficient to build this program. The save command overwrites
books-demo.txt in the working directory; use a directory where that name
does not contain data you need.
File library.hpp:
#ifndef FOUNDATION_LIBRARY_HPP
#define FOUNDATION_LIBRARY_HPP
#include <iosfwd>
#include <string>
#include <vector>
struct Book {
int id;
std::string title;
};
bool parsePositiveId(const std::string& token, int& id);
bool parseBookLine(const std::string& line, Book& book);
class Library {
std::vector<Book> books_;
public:
bool add(int id, const std::string& title);
const Book* find(int id) const;
void sortByTitle();
const std::vector<Book>& books() const;
bool load(std::istream& input);
bool save(std::ostream& output) const;
bool loadFile(const std::string& path);
bool saveFile(const std::string& path) const;
};
#endifFile library.cpp:
#include "library.hpp"
#include <algorithm>
#include <cctype>
#include <fstream>
#include <istream>
#include <ostream>
#include <sstream>
namespace {
bool validTitle(const std::string& title) {
return !title.empty() &&
!std::isspace(static_cast<unsigned char>(title.front())) &&
!std::isspace(static_cast<unsigned char>(title.back())) &&
title.find_first_of("\r\n") == std::string::npos;
}
bool titleBefore(const Book& left, const Book& right) {
if (left.title == right.title) {
return left.id < right.id;
}
return left.title < right.title;
}
}
bool parsePositiveId(const std::string& token, int& id) {
if (token.empty() || token.find_first_not_of("0123456789") != std::string::npos) {
return false;
}
std::istringstream input(token);
int candidate = 0;
if (!(input >> candidate) || candidate <= 0) {
return false;
}
id = candidate;
return true;
}
bool parseBookLine(const std::string& line, Book& book) {
std::string record = line;
if (!record.empty() && record.back() == '\r') {
record.pop_back();
}
if (record.find_first_of("\r\n") != std::string::npos) {
return false;
}
std::istringstream input(record);
std::string token;
Book candidate{0, ""};
if (!(input >> token) || !parsePositiveId(token, candidate.id)) {
return false;
}
input >> std::ws;
if (!std::getline(input, candidate.title) || !validTitle(candidate.title)) {
return false;
}
book = candidate;
return true;
}
bool Library::add(int id, const std::string& title) {
if (id <= 0 || !validTitle(title) || find(id) != nullptr) {
return false;
}
books_.push_back(Book{id, title});
return true;
}
const Book* Library::find(int id) const {
for (const Book& book : books_) {
if (book.id == id) {
return &book;
}
}
return nullptr;
}
void Library::sortByTitle() {
std::sort(books_.begin(), books_.end(), titleBefore);
}
const std::vector<Book>& Library::books() const {
return books_;
}
bool Library::load(std::istream& input) {
if (!input) {
return false;
}
Library candidate;
std::string line;
while (std::getline(input, line)) {
Book book{0, ""};
if (!parseBookLine(line, book) || !candidate.add(book.id, book.title)) {
return false;
}
}
if (input.bad() || !input.eof()) {
return false;
}
books_.swap(candidate.books_);
return true;
}
bool Library::save(std::ostream& output) const {
if (!output) {
return false;
}
for (const Book& book : books_) {
output << book.id << ' ' << book.title << '\n';
}
output.flush();
return static_cast<bool>(output);
}
bool Library::loadFile(const std::string& path) {
std::ifstream input(path);
return input && load(input);
}
bool Library::saveFile(const std::string& path) const {
std::ofstream output(path, std::ios::trunc);
if (!output) {
return false;
}
const bool written = save(output);
output.close();
return written && static_cast<bool>(output);
}File main.cpp:
#include "library.hpp"
#include <iostream>
#include <sstream>
#include <string>
bool noMoreArguments(std::istream& input) {
input >> std::ws;
return input.eof();
}
int main() {
Library library;
const std::string path = "books-demo.txt";
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream input(line);
std::string command;
if (!(input >> command)) {
continue;
}
if (command == "add") {
std::string record;
std::getline(input, record);
Book book{0, ""};
if (parseBookLine(record, book) && library.add(book.id, book.title)) {
std::cout << "Added: " << book.id << '\n';
} else {
std::cout << "Invalid book or duplicate ID\n";
}
} else if (command == "find") {
std::string token;
int id = 0;
if (!(input >> token) || !parsePositiveId(token, id) ||
!noMoreArguments(input)) {
std::cout << "Invalid ID\n";
continue;
}
const Book* book = library.find(id);
if (book != nullptr) {
std::cout << book->id << " | " << book->title << '\n';
} else {
std::cout << "Not found\n";
}
} else if (command == "list" && noMoreArguments(input)) {
if (library.books().empty()) {
std::cout << "No books\n";
}
for (const Book& book : library.books()) {
std::cout << book.id << " | " << book.title << '\n';
}
} else if (command == "sort" && noMoreArguments(input)) {
library.sortByTitle();
std::cout << "Sorted by title\n";
} else if (command == "save" && noMoreArguments(input)) {
std::cout << (library.saveFile(path) ? "Saved: " : "Save failed: ")
<< path << '\n';
} else if (command == "load" && noMoreArguments(input)) {
if (library.loadFile(path)) {
std::cout << "Loaded: " << library.books().size() << '\n';
} else {
std::cout << "Load failed; books unchanged\n";
}
} else if (command == "quit" && noMoreArguments(input)) {
return 0;
} else {
std::cout << "Unknown command or extra arguments\n";
}
}
if (std::cin.bad() || !std::cin.eof()) {
std::cerr << "Input failed\n";
return 1;
}
return 0;
}Compile using GCC or Clang from the directory containing the files:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror main.cpp library.cpp -o booksRun ./books on Linux/macOS or .\books.exe in PowerShell.
Enter these lines; the program prints no prompt:
add 2 Lifetime
add 1 C++ Basics
add 2 Duplicate
find 1
find 9
sort
list
save
add 3 Templates
load
list
quitOutput when saving/loading succeed:
Added: 2
Added: 1
Invalid book or duplicate ID
1 | C++ Basics
Not found
Sorted by title
1 | C++ Basics
2 | Lifetime
Saved: books-demo.txt
Added: 3
Loaded: 2
1 | C++ Basics
2 | LifetimeThe saved file has two lines: 1 C++ Basics and 2 Lifetime.
Templates disappears after load because it was added after the save.
Load failed; books unchanged means current data was preserved, not that
the source file has been repaired.
5. Common mistakes
Compiling only
main.cpp, or putting ordinary function definitions in the header.Accepting duplicate/partial IDs such as
1abc, or looping forever on bad input.Indexing at
size(): a last element exists only when nonempty, atsize() - 1.Keeping a pointer from
findthrough add/sort/load without checking validity.Clearing current books before validating the entire replacement file.
Assuming
loadappends orquitsaves; ignoring write/close failures.
6. Practice
Implement the three files from the contract before consulting the solution. Test an empty library, add/find ID
1, duplicate/negative IDs, an empty title and an overflowing ID. Rejection must preserve data. Equal titles with different IDs are allowed.Test save/load round trips using
ostringstreamandistringstream. Duplicate IDs, a blank line, or a valid line followed by a bad one must preserve the old list. A valid empty file must empty the library.Copy a library, add to the copy and verify the original is unchanged. Add equal titles with IDs in reverse order; sorting must put the smaller ID first. Explain how finding, adding and loading costs grow.
Repair three bugs before executing: indexing
books()[books().size()]; returning afindpointer from a localLibraryabout to be destroyed; and accepting1abcafter extracting only anint. Use bounds checks/at(), a sufficiently long-lived owner or a returned value, and whole-token validation. Use a debugger to inspect the triggering input; memory tools help but cannot prove every defect has been removed.Add a
countcommand, then optionally deletion by ID. Find needed pointers again after deletion; do not retain iterators across vector mutations. Specify the missing-ID behavior before implementing it.
7. Self-check
Why does a file with a valid first book and then a duplicate ID preserve old data? Answer: loading validates every record in
candidate. Rejection occurs before the final swap, so the current library has not changed.After
const Book* p = library.find(1), can you always calladdand then usep? Answer: no. Adding can reallocate and invalidate the pointer. Find the ID again after mutation, and never delete a borrowed pointer. Sorting can also change the book at that address without reallocation.Why must the build include both
main.cppandlibrary.cpp? Answer: the header supplies declarations for compilation, butLibrarydefinitions live inlibrary.cpp. Linking needs code from both translation units to produce the complete program.
Sample code
Source file
cpp98_foundation/27_stage4_practice/main.cpp
#include "library.hpp"
#include <iostream>
#include <sstream>
#include <string>
bool noMoreArguments(std::istream& input) {
input >> std::ws;
return input.eof();
}
int main() {
Library library;
const std::string path = "books-demo.txt";
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream input(line);
std::string command;
if (!(input >> command)) {
continue;
}
if (command == "add") {
std::string record;
std::getline(input, record);
Book book{0, ""};
if (parseBookLine(record, book) && library.add(book.id, book.title)) {
std::cout << "Added: " << book.id << '\n';
} else {
std::cout << "Invalid book or duplicate ID\n";
}
} else if (command == "find") {
std::string token;
int id = 0;
if (!(input >> token) || !parsePositiveId(token, id) ||
!noMoreArguments(input)) {
std::cout << "Invalid ID\n";
continue;
}
const Book* book = library.find(id);
if (book != nullptr) {
std::cout << book->id << " | " << book->title << '\n';
} else {
std::cout << "Not found\n";
}
} else if (command == "list" && noMoreArguments(input)) {
if (library.books().empty()) {
std::cout << "No books\n";
}
for (const Book& book : library.books()) {
std::cout << book.id << " | " << book.title << '\n';
}
} else if (command == "sort" && noMoreArguments(input)) {
library.sortByTitle();
std::cout << "Sorted by title\n";
} else if (command == "save" && noMoreArguments(input)) {
std::cout << (library.saveFile(path) ? "Saved: " : "Save failed: ")
<< path << '\n';
} else if (command == "load" && noMoreArguments(input)) {
if (library.loadFile(path)) {
std::cout << "Loaded: " << library.books().size() << '\n';
} else {
std::cout << "Load failed; books unchanged\n";
}
} else if (command == "quit" && noMoreArguments(input)) {
return 0;
} else {
std::cout << "Unknown command or extra arguments\n";
}
}
if (std::cin.bad() || !std::cin.eof()) {
std::cerr << "Input failed\n";
return 1;
}
return 0;
}