C++
Putting it together
Combine all layers into a working app.
Putting it together: the full program
In the final lesson we combine all pieces: the Task class, the printItem template, std::vector and file I/O. The program creates tasks, marks one done, saves to file, loads back and counts completed tasks.
This is the intermediate final: OOP + template + STL + file I/O in one program. The flow: create three tasks, mark the first done with tasks[0].done = true, save to file with std::ofstream, load back with std::ifstream and count completed with if (done). Each piece was learned in previous lessons; now we bring them all together.
Counting completed tasks
When loading back, you count only completed tasks with if (done). This is the final step of the save-load-count pattern.
Example: while (in >> title >> done) { if (done) count++; }. Here each loaded task's done flag is checked; if true the counter is incremented. Because we set tasks[0].done = true before saving, the first task is written as 1 in the file. When reading back, done is read as 1 (that is true) and counted. The result is 1.
Exercise Write the full program
After the Task class and printItem template in the starting code, in main: create a std::vector<Task>, add three tasks (Homework, Sport, Book). Mark the first done with tasks[0].done = true;. Save to tasks.txt with std::ofstream. Load back with std::ifstream and count completed with if (done), print with std::cout.
Show example solution
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
class Task {
public:
std::string title;
bool done;
Task(std::string t) : title(t), done(false) {}
};
template <typename T>
void printItem(const T& item) {
std::cout << item;
}
int main() {
std::vector<Task> tasks;
tasks.push_back(Task("Homework"));
tasks.push_back(Task("Sport"));
tasks.push_back(Task("Book"));
tasks[0].done = true;
std::ofstream out("tasks.txt");
for (const auto& t : tasks) {
out << t.title << " " << t.done << "\n";
}
out.close();
std::ifstream in("tasks.txt");
std::string title;
bool done;
int c = 0;
while (in >> title >> done) {
if (done) c++;
}
std::cout << c;
return 0;
}
Test yourself
-
Match each piece to its technology
- class Task
- OOP
- template <typename T>
- Template
- std::vector
- STL
- std::ofstream
- File I/O
-
Which four topics does this project combine?
class Task {};
template <typename T>
std::vector<Task>;
std::ofstream;
- HTML, CSS, JS, SQL
- Only OOP
- OOP, template, STL, file I/O
- Only file I/O
Show answer
OOP, template, STL, file I/O — The project combines OOP, template, STL and file I/O.
-
Count completed
while (in >> title >> done) { if (____) count++; }
Show answer
while (in >> title >> done) { if (done) count++; }
Next lesson: Intermediate section exam