1. Predict before running
Consider a missing file, an empty file, and a readable file containing one line of text.
For each, name the status, the local class objects that get constructed, their destruction
order, and whether a file was open. Write your answers before revealing the check.
Check your prediction
| Input | Status |
Objects and cleanup |
| Missing file | 1 |
Construct and destroy input only. No file opened. |
| Empty file | 2 |
Construct input, then line.
Destroy line, then input; the open file closes. |
| One text line | 0 |
Same construction and destruction order as the empty file.
Print the line before cleanup. |
The return 2 path needs no special cleanup branch.
Check the lifetime rule.
2. Skip empty lines
Edit exercise.cpp to print the
first nonempty line. Empty means zero characters: spaces and tabs count as
content. A final line without a newline must work too.
Keep statuses 0, 1, and 64. Return 2 if no nonempty line is extracted, including an empty
file or a file containing only empty lines. Use std::getline and
line.empty(); add no manual close, free,
new, or delete.
Run the checks from the workspace root; they compile your source automatically:
python3 -m unittest discover \
-s exercises/0001-scope-cleanup \
-p 'test_exercise.py' -v
The starter intentionally fails the leading-empty-lines and all-empty-lines cases.
The other checks pass. The checks assess output and exit status; your explanation and
a source review establish how cleanup works.
Show a hint, without the solution
Use a while condition that calls std::getline(input, line).
Inside the loop, line.empty() tells you whether the extracted string
has zero characters. Decide where a successful return belongs, and what should
happen when the loop ends.
The empty check.
For a manual trial,
leading-empty.txt
starts with two empty lines; your completed program should print keep this line.
3. Explain it from memory
Close the lesson. Explain why an early return can be safe here, and what would differ
if input were a raw FILE* returned by fopen.
At the start of your next session, try that explanation again before reopening your notes.