Skip to content

Assemble the Study Planner

The Course
•
30 min study

You have every piece of the planner: a parser that validates a line, a function that adds a task within the limit, and a summary that reads the stored tasks. Assembling them is where small decisions matter most. Where does a rejected line get counted? What happens to the stored tasks when line 57 is bad? When is it safe to print? This lesson walks through main.cpp and explains why each step is where it is.

The flow has three stages. Read: main.cpp takes one line at a time from std::cin. Accept or reject: parse_task validates the whole record before changing its output, and add_task checks the record and the 100-task limit before copying it into the vector. Report: summarize reads the stored tasks through a const reference, and main prints the list and the totals.

Predict and run

Predict before running C++
#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{25, 0, 10};
    int total = 0;
    for (int value : values) {
        if (value < 1 || value > 180) {
            continue;
        }
        total += value;
    }
    std::cout << total << "\n";
    return 0;
}
Check your prediction
Text
35

continue skips the rest of the current iteration and moves on to the next value. The 0 is rejected without stopping the loop, so the 10 after it still counts. Move total += value; above the if and the 0 is added before it is checked: harmless here, but with 500 it would silently inflate the total. Validation must come before any effect.

The input loop, line by line

The heart of main.cpp is this loop:

C++
while (std::getline(std::cin, line)) {
    if (!line.empty() && line.back() == '\r') {
        line.pop_back();
    }
    Task task;
    if (!parse_task(line, task) || !add_task(tasks, task)) {
        ++rejected;
    }
}
  • Whole lines first. Each record is read with std::getline, so a malformed line is consumed completely and cannot confuse the next read.
  • Carriage returns. Text saved on Windows ends lines with \r\n. getline removes the \n but keeps the \r, which would otherwise end up in the title. The !line.empty() check comes first so line.back() is never called on an empty string, which would be undefined behavior.
  • A fresh Task every iteration. task is declared inside the loop body, so it is created and destroyed once per line. Nothing from a previous line can leak into the next one.
  • Short-circuit ||. If parsing fails, add_task never runs, so an invalid record can never be stored. If parsing succeeds but the planner is full, add_task fails. Either way the line is counted once, as rejected.

Inside parse_task, a separator character must follow the minutes and the flag, which stops 25+0 from being read as two adjacent numbers and 0Title from being accepted as a flag and a title. A fresh string stream is created for each line, so a failed parse leaves no sticky failure behind.

After the loop

The loop ends when getline fails. Usually that is a normal end-of-file, but it can also be a real read error. std::cin.bad() distinguishes the two: it is true only for a serious failure, and then main writes a message to std::cerr and returns 1 instead of printing a report built from partial data.

The report is printed only after all input has been read, because the totals are not known until the end. The listing loop uses const Task&, and summarize takes const std::vector<Task>&, so the reporting stage cannot change a task.

Why the limit is 100

The 100-task limit bounds the report's arithmetic: at most 100 times 180, or 18,000 minutes, so no total can approach the largest int. It is a product rule, not a memory limit for every input line. getline can still allocate space for one very long rejected line, and the project's checks include a 1,000-character line to prove it is rejected without affecting the next one. The program stores nothing after a run ends.

Practice

Exercise

Your turn

Simulate the accept-or-reject stage with plain durations. From the values 25, 0, 10, 181 and 30, store valid durations (1 through 180) in a vector, but never more than 2. Count everything else as rejected, including valid values that arrive when the vector is full. Print:

  • Accepted: 2
  • Rejected: 3
  • Stored: 25 10

Keep reading after every rejection.

Your workspace C++
#include <iostream>
#include <vector>

int main() {
    std::vector<int> input{25, 0, 10, 181, 30};
    const std::size_t limit = 2;
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Each value belongs to exactly one category. A value is stored only if it is valid and there is room; failing either check makes it rejected.

Hint 2: a first step

Write if (value < 1 || value > 180 || stored.size() >= limit) { ++rejected; continue; }, then push_back the value.

Show one solution
Run the solution C++
#include <iostream>
#include <vector>

int main() {
    std::vector<int> input{25, 0, 10, 181, 30};
    const std::size_t limit = 2;
    std::vector<int> stored;
    int rejected = 0;
    for (int value : input) {
        if (value < 1 || value > 180 || stored.size() >= limit) {
            ++rejected;
            continue;
        }
        stored.push_back(value);
    }
    std::cout << "Accepted: " << stored.size() << "\n";
    std::cout << "Rejected: " << rejected << "\n";
    std::cout << "Stored:";
    for (int value : stored) {
        std::cout << " " << value;
    }
    std::cout << "\n";
    return 0;
}
Text
Accepted: 2
Rejected: 3
Stored: 25 10

The 30 is a valid duration, but it arrives when the vector already holds 2 values, so the capacity check rejects it, just as the planner rejects a valid 101st task. The accepted count comes from stored.size() rather than a separate counter, so the two can never disagree. Now run the real planner below and trace the same stages.

Run the complete planner

The input box holds the acceptance example from the brief.

Study planner C++
#include "planner.h" #include <iostream> int main() { std::vector<Task> tasks; std::string line; int rejected = 0; while (std::getline(std::cin, line)) { // Accept both LF and CRLF text pasted from a local file. if (!line.empty() && line.back() == '\r') { line.pop_back(); } Task task; if (!parse_task(line, task) || !add_task(tasks, task)) { ++rejected; } } if (std::cin.bad()) { std::cerr << "Could not read input\n"; return 1; } for (const Task& task : tasks) { std::cout << (task.done ? "Done: " : "Todo: ") << task.title << " (" << task.minutes << " min)\n"; } const Summary result = summarize(tasks); std::cout << "Tasks: " << tasks.size() << '\n'; std::cout << "Planned: " << result.planned << " minutes\n"; std::cout << "Completed: " << result.completed << " minutes\n"; std::cout << "Remaining: " << result.remaining << " minutes\n"; std::cout << "Rejected: " << rejected << '\n'; return 0; } #include "planner.h" #include <sstream> bool valid_task(const Task& task) { return task.minutes >= 1 && task.minutes <= 180 && !task.title.empty() && task.title.size() <= 40 && task.title.find_first_not_of(" \t") != std::string::npos && task.title.find_first_of("\r\n") == std::string::npos; } bool parse_task(const std::string& line, Task& out) { if (line.find_first_of("\r\n") != std::string::npos) { return false; } std::istringstream input(line); Task candidate; int done = 0; char separator = '\0'; if (!(input >> candidate.minutes) || !input.get(separator) || (separator != ' ' && separator != '\t')) { return false; } if (!(input >> done) || (done != 0 && done != 1)) { return false; } // Require whitespace between the done flag and the title. if (!input.get(separator) || (separator != ' ' && separator != '\t')) { return false; } std::getline(input >> std::ws, candidate.title); candidate.done = done == 1; if (!valid_task(candidate)) { return false; } out = candidate; return true; } bool add_task(std::vector<Task>& tasks, const Task& task) { if (tasks.size() >= 100 || !valid_task(task)) { return false; } tasks.push_back(task); return true; } Summary summarize(const std::vector<Task>& tasks) { Summary result; for (const Task& task : tasks) { result.planned += task.minutes; if (task.done) { result.completed += task.minutes; } else { result.remaining += task.minutes; } } return result; } bool complete_task(std::vector<Task>& tasks, std::size_t index) { if (index >= tasks.size()) { return false; } tasks[index].done = true; return true; } #ifndef STUDY_PLANNER_H #define STUDY_PLANNER_H #include <string> #include <vector> struct Task { std::string title; int minutes = 0; bool done = false; }; struct Summary { int planned = 0; int completed = 0; int remaining = 0; }; // One line: minutes, 0/1 done flag, then a title of 1..40 characters. // Durations are 1..180. Failure leaves out unchanged. bool parse_task(const std::string& line, Task& out); // At most 100 tasks. Rejection leaves the vector unchanged. bool add_task(std::vector<Task>& tasks, const Task& task); // Caller supplies tasks accepted by add_task. Summary summarize(const std::vector<Task>& tasks); // Invalid indexes fail without changing any task. Repeating completion is safe. bool complete_task(std::vector<Task>& tasks, std::size_t index); #endif 25 0 Read chapter 10 1 Review notes bad line 180 0 Practice
Check your prediction
Text
Todo: Read chapter (25 min)
Done: Review notes (10 min)
Todo: Practice (180 min)
Tasks: 3
Planned: 215 minutes
Completed: 10 minutes
Remaining: 205 minutes
Rejected: 1

Now challenge it. Clear the input and run again: every total should be zero. Place a bad line before 25 0 Read and check that Read is still accepted. Try 25+0 Title, 0 0 Zero and a 41-character title, predicting the rejected count first. Change one completion flag to 1 and explain which totals change: planned stays the same, and completed plus remaining always equals planned.

Was this article helpful?

Your response is saved on this device.