Thuta Learning
C++
ProjectsProgrammingBeginner

Mini Project: Student Manager - Part 3

C++Lesson 3345 min

What you'll walk away with

  • Call clear() and ignore() in the right order so a stream works again after a failed read
  • Catch exceptions thrown by the model at the edge of the UI and keep the program running
  • Sort with std::sort and a lambda comparator that breaks ties
  • Save the student list to a text file and load it back while skipping damaged lines

Explain it simply

Explain it simply

After Part 2 the program works, but it is fragile. One mistyped "abc" in the marks can end the whole session, and closing the program loses every student. Part 3 fixes both and adds sorting by marks.

Think of a supermarket checkout. When a barcode does not scan, the shop does not close; the cashier says "scan it again" and moves on to the next item. At closing time the day's sales are written down, so tomorrow starts where today ended. Handling an error and carrying on, and writing the data down, are the heart of Part 3.

Problem → Why → Solution

The problem: one bad line ruins the session

Run Part 2's program with a script containing "1 Bo 2 abc". in >> marks cannot read "abc" as a double, so it sets marks to 0 and puts the stream into a failed state. The code never checks, so Bo is added with 0 marks and "Added Bo" is printed: wrong data. Then in >> choice in the menu loop fails too, and the loop quietly ends. Daw is never added and the list is never shown.

Marks of 120 are worse. Part 1's constructor throws std::invalid_argument, nobody catches it, and the program is terminated, possibly before buffered output even appears. On top of that, all data lives only in memory, so closing the program loses everything.

part2_add.cpp
// Part 2's add command, unchanged, fed one bad line.
void addFromInput(std::istream& in, StudentManager& manager) {
    std::string name;
    int roll = 0;
    double marks = 0.0;
    in >> name >> roll >> marks;  // "abc": marks becomes 0, the stream fails
    if (manager.add(Student(name, roll, marks))) {
        std::cout << "Added " << name << '\n';  // "Added Bo" with 0 marks!
    }
}

// keys: "1 Aye 1 78.5\n1 Bo 2 abc\n1 Daw 4 91\n2\n3\n"
// Output: Added Aye, Added Bo ... and then nothing.
// The failed stream makes while (in >> choice) false: Daw is never
// added, the list is never shown, and nothing was ever written to disk.
// "1 Chit 3 120" would be worse: an uncaught invalid_argument ends the program.

Why does a stream stay failed?

When a stream meets text it cannot convert, it sets failbit and leaves that text in its buffer. While failbit is set, every further read does nothing and fails immediately. That is deliberate, so an error cannot slip by unnoticed; it also means recovery is your job: clear() the flags and ignore() the offending text.

Core concept: recover, sort, persist

1. Catch errors at the edge of the UI

The Student constructor throws on bad marks, and that is right: Student does not know how to talk to the user. addFromInput(), which does talk to the user, wraps the read and the add in a try block and throws its own std::runtime_error when the format is wrong. A single catch (const std::exception& e) handles both that runtime_error and the constructor's invalid_argument, because both derive from std::exception.

2. Repair the stream: clear() first, then ignore()

recover() calls in.clear() to reset the error flags and then in.ignore(max, '\n') to throw away the rest of the line. The order matters, because ignore() also does nothing on a failed stream. Without the ignore, "abc" would stay in the buffer and the next read would hit it and fail again. The menu loop uses the same helper and checks in.eof() to tell "input ended" apart from "wrong key".

3. Sort predictably

sortByMarks() calls std::sort with a lambda comparator. The comparator answers only "should a come before b?" and must be false for two equal elements (use >, never >=). std::sort is not stable, so two students with equal marks could come out in either order; the roll number is added as a second key to make the result predictable.

4. Save and load

saveToFile() writes one "roll marks name" line per student. The name goes last so names with spaces can be read back, and std::format("{}") writes each double in its shortest round-trip form. loadFromFile() treats a missing file as the first run and returns 0, then parses each line through an istringstream. Data from disk is just another input, so the Student constructor checks it again and damaged lines are skipped.

Mental model: report, repair, carry on
  1. Read; on failure, report it
  2. clear() flags, then ignore() the line
  3. Model throws? Catch at the menu edge
  4. Load at start, save when the loop ends

A bad command should cost exactly that one command, never the session and never the saved data.

General pattern

cpp
try {
    if (!(in >> a >> b)) throw std::runtime_error("bad format");
    use(a, b);  // may throw as well
} catch (const std::exception& e) {
    report(e.what());
    in.clear();  // 1. reset the error flags first
    in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // 2. drop the line
}

std::sort(v.begin(), v.end(), [](const T& x, const T& y) { return key(x) > key(y); });
std::ofstream out(path);  // one record per line, free text last
std::ifstream in(path);   // missing file: first run, start empty

Put the read and its use inside try, catch errors once through std::exception, and repair the stream with clear() and then ignore(). A sort comparator only answers "does a go first?", and a file holds one record per line.

Part 3 code: the complete program

Student is unchanged since Part 1. StudentManager gains sortByMarks(), saveToFile() and loadFromFile(); the menu gains option 5 (sort), and option 3 becomes Save & Exit. main() simulates two runs of the program. The first run contains three bad lines: "abc" as marks, marks of 120, and "x" as a menu key. Then it prints the saved file and appends two damaged lines, as if someone had edited the file by hand. The second run loads the file, shows the list and saves again.

Where is the data file?

The example uses a uniquely named file in std::filesystem::temp_directory_path() and deletes it at the end, so every run prints the same result. In your own program, use a fixed path such as "students.txt" and drop the fs::remove() call.

student_manager.cpp
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

namespace fs = std::filesystem;

class Student {
public:
    Student(std::string name, int roll, double marks)
        : name_(std::move(name)), roll_(roll), marks_(checkedMarks(marks)) {}

    const std::string& getName() const { return name_; }
    int getRoll() const { return roll_; }
    double getMarks() const { return marks_; }

    void setMarks(double marks) { marks_ = checkedMarks(marks); }

private:
    static double checkedMarks(double marks) {
        if (marks < 0.0 || marks > 100.0) {
            throw std::invalid_argument("marks must be between 0 and 100");
        }
        return marks;
    }

    std::string name_;
    int roll_;
    double marks_;
};

class StudentManager {
public:
    bool add(const Student& student) {
        if (findByRoll(student.getRoll()) != nullptr) {
            return false;
        }
        students_.push_back(student);
        return true;
    }

    const Student* findByRoll(int roll) const {
        for (const Student& s : students_) {
            if (s.getRoll() == roll) {
                return &s;
            }
        }
        return nullptr;
    }

    void displayAll() const {
        if (students_.empty()) {
            std::cout << "No students yet.\n";
            return;
        }
        std::cout << "Roll  Name     Marks\n";
        for (const Student& s : students_) {
            std::cout << std::format("{:>4}  {:<8}{:>6.1f}\n",
                                     s.getRoll(), s.getName(), s.getMarks());
        }
    }

    std::size_t count() const { return students_.size(); }

    void sortByMarks() {
        std::sort(students_.begin(), students_.end(),
                  [](const Student& a, const Student& b) {
                      if (a.getMarks() != b.getMarks()) {
                          return a.getMarks() > b.getMarks();  // highest first
                      }
                      return a.getRoll() < b.getRoll();  // tie: lower roll first
                  });
    }

    void saveToFile(const fs::path& path) const {
        std::ofstream out(path);
        if (!out) {
            throw std::runtime_error("cannot open the data file for writing");
        }
        for (const Student& s : students_) {
            // name goes last so a later version can allow spaces in it
            out << std::format("{} {} {}\n", s.getRoll(), s.getMarks(), s.getName());
        }
    }

    std::size_t loadFromFile(const fs::path& path) {
        std::ifstream in(path);
        if (!in) {
            return 0;  // first run: there is no file yet
        }
        std::size_t loaded = 0;
        std::string line;
        while (std::getline(in, line)) {
            std::istringstream fields(line);
            int roll = 0;
            double marks = 0.0;
            std::string name;
            if (!(fields >> roll >> marks) || !std::getline(fields >> std::ws, name)) {
                std::cout << "Skipped a damaged line: " << line << '\n';
                continue;
            }
            try {
                loaded += add(Student(name, roll, marks)) ? 1 : 0;
            } catch (const std::invalid_argument& e) {
                std::cout << "Skipped " << name << ": " << e.what() << '\n';
            }
        }
        return loaded;
    }

private:
    std::vector<Student> students_;
};
// After a failed read: clear the error flags, then throw away the rest of the line.
void recover(std::istream& in) {
    in.clear();
    in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

void addFromInput(std::istream& in, StudentManager& manager) {
    std::string name;
    int roll = 0;
    double marks = 0.0;
    try {
        if (!(in >> name >> roll >> marks)) {
            throw std::runtime_error("expected: name roll marks");
        }
        if (!manager.add(Student(name, roll, marks))) {
            throw std::runtime_error(std::format("roll {} already exists", roll));
        }
        std::cout << "Added " << name << '\n';
    } catch (const std::exception& e) {
        std::cout << "Error: " << e.what() << '\n';
        recover(in);
    }
}

void searchFromInput(std::istream& in, const StudentManager& manager) {
    int roll = 0;
    if (!(in >> roll)) {
        std::cout << "Error: roll must be a number\n";
        recover(in);
        return;
    }
    if (const Student* found = manager.findByRoll(roll)) {
        std::cout << std::format("Found: {} ({:.1f})\n",
                                 found->getName(), found->getMarks());
    } else {
        std::cout << "Roll " << roll << " not found\n";
    }
}

void runMenu(std::istream& in, StudentManager& manager) {
    while (true) {
        int choice = 0;
        if (!(in >> choice)) {
            if (in.eof()) {
                return;  // input ended: treat it like Exit
            }
            std::cout << "Error: type a menu number\n";
            recover(in);
            continue;
        }
        std::cout << "> " << choice << '\n';
        switch (choice) {
        case 1: addFromInput(in, manager); break;
        case 2: manager.displayAll(); break;
        case 3: return;  // Save & Exit: the caller saves
        case 4: searchFromInput(in, manager); break;
        case 5:
            manager.sortByMarks();
            std::cout << "Sorted by marks (highest first)\n";
            break;
        default: std::cout << "Invalid choice: " << choice << '\n';
        }
    }
}

void runSession(const fs::path& file, const std::string& keys) {
    StudentManager manager;
    const std::size_t loaded = manager.loadFromFile(file);
    std::cout << "Loaded " << loaded << " student(s)\n";
    std::istringstream script(keys);
    runMenu(script, manager);
    manager.saveToFile(file);  // runs after Exit and also when input just ends
    std::cout << "Saved " << manager.count() << " student(s). Goodbye!\n";
}

int main() {
    auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
    const fs::path file =
        fs::temp_directory_path() / std::format("students-{}.txt", stamp);

    std::cout << "== first run ==\n";
    runSession(file, "1 Aye 1 78.5\n1 Bo 2 abc\n1 Chit 3 120\nx\n"
                     "1 Daw 4 91\n1 Bo 2 85\n1 Ei 5 64\n5\n3\n");

    std::cout << "== file contents ==\n";
    std::ifstream saved(file);
    for (std::string line; std::getline(saved, line);) {
        std::cout << line << '\n';
    }
    saved.close();

    {
        std::ofstream edit(file, std::ios::app);  // someone edits the file by hand
        edit << "7 abc Hla\n8 130 Mya\n";
    }

    std::cout << "== second run ==\n";
    runSession(file, "2\n4 7\n3\n");
    fs::remove(file);
}

Code breakdown

  1. One catch for both kinds of error} catch (const std::exception& e) {

    "abc" causes the runtime_error "expected: name roll marks", and 120 causes the constructor's invalid_argument. Both land here, print their message and call recover().

  2. Reset the flagsin.clear();

    Removes failbit; without this, ignore() and every later read would fail at once. The ignore(max, '\n') that follows discards the leftover "abc", so "1 Daw 4 91" is read normally.

  3. Tie-break on rollreturn a.getRoll() < b.getRoll(); // tie: lower roll first

    Different marks are decided by the line above. Only equal marks reach this line, which puts the lower roll first, so the order is the same on every run.

  4. One line per student, name lastout << std::format("{} {} {}\n", s.getRoll(), s.getMarks(), s.getName());

    This produces lines such as "1 78.5 Aye" in the file. {} writes 91.0 as 91, which reads back as exactly the same value.

  5. Rest of the line is the nameif (!(fields >> roll >> marks) || !std::getline(fields >> std::ws, name)) {

    Two numbers are read, std::ws skips the spaces, and getline takes the rest of the line as the name. "7 abc Hla" fails here and prints "Skipped a damaged line".

  6. Missing file means first runreturn 0; // first run: there is no file yet

    On the first run there is no file yet, so the program reports "Loaded 0 student(s)". That is not an error, just an empty start.

  7. Save however the loop endedmanager.saveToFile(file); // runs after Exit and also when input just ends

    Whether runMenu returned because of option 3 or because the input ran out, the save runs, so data is kept even when nobody chose Exit.

You should see
== first run ==
Loaded 0 student(s)
> 1
Added Aye
> 1
Error: expected: name roll marks
> 1
Error: marks must be between 0 and 100
Error: type a menu number
> 1
Added Daw
> 1
Added Bo
> 1
Added Ei
> 5
Sorted by marks (highest first)
> 3
Saved 4 student(s). Goodbye!
== file contents ==
4 91 Daw
2 85 Bo
1 78.5 Aye
5 64 Ei
== second run ==
Skipped a damaged line: 7 abc Hla
Skipped Mya: marks must be between 0 and 100
Loaded 4 student(s)
> 2
Roll  Name     Marks
   4  Daw       91.0
   2  Bo        85.0
   1  Aye       78.5
   5  Ei        64.0
> 4
Roll 7 not found
> 3
Saved 4 student(s). Goodbye!
The path of one add command
  1. Read name, roll and marks
  2. Build the Student (may throw)
  3. add() refuses a duplicate roll

All checks pass

Added <name>

Anything fails

Error: <reason>, then clear() + ignore()

Making saves survive a crash

This program saves when the loop ends. That covers Exit and the end of input, but not a crash or the user pressing Ctrl+C: changes since the last save are lost. For data that matters, save after every successful add; for a few hundred students, rewriting the whole file is fast.

The second trap is a crash in the middle of writing, which can leave a half-written file. The usual fix is to write the new data to a temporary file next to the real one, check that writing succeeded, and then rename it over the old file, so a crash leaves either the old file or the new one, never a mix. How rename replaces an existing target can differ between operating systems, so test it on every platform you support.

One more thing to notice: loadFromFile() skips damaged lines, and the next save rewrites the file without them. That is how Hla's and Mya's lines disappear in the example. A real application would first copy a damaged file aside as a backup.

In real projects

In real projects

Most desktop and command-line tools follow this Part 3 shape: load at start, save at the end, skip and report damaged data. Think of a text editor's settings, a game's save file or a shop's daily export. For a few simple fields a text format is enough. Once data becomes nested, or names may contain quotes, teams usually switch to a JSON or CSV library, or to an embedded database such as SQLite, rather than writing quoting and escaping by hand.

Validating at the boundary and turning errors into messages a user understands is universal too. A web server does not die because of one malformed request; it answers 400 and serves the next one. Sorting with a consistent tie-break matters in reports, rankings and exports, so two runs over the same data can be diffed without noise.

Common mistakes

Common mistakes

Calling clear() without ignore(), or the other way round

With clear() alone, "abc" stays in the buffer, the next read fails on it again, and the loop can print error messages forever. Calling ignore() before clear() does nothing either, because the stream is still failed. Keep the order, clear() then ignore(), inside one helper such as recover().

Saving only on the Exit path

Calling save only inside case 3 loses the whole session when the input simply ends, when an exception leaves the loop, or when the program crashes. Save after the loop, and for important data, after every change.

Putting a field that may contain spaces in the middle

With a "roll name marks" format read by fin >> roll >> name >> marks, the line "5 Ei Mon 64" gives name "Ei" and then fails trying to read "Mon" as marks. Put free text last and read it with getline, or use a delimiter such as a comma.

Using >= in the comparator

std::sort requires a strict weak ordering, which means comp(a, a) must be false. >= returns true for equal marks, which is undefined behaviour and can produce a wrong order or even out-of-range reads. Use > and settle ties with a second key.

Mini challenge

Import students from a CSV file

Write importCsv(), which imports students from a CSV file with the header "roll,name,marks". Names may contain spaces, and numbers must be parsed strictly: "88x" must not be accepted as 88. Report every bad line with its line number and reason, then skip it. Test file content: roll,name,marks / 1,Aye Aye,78.5 / 2,Bo,91 / (blank line) / 3,Chit,abc / 4,Daw,88x / 5,Ei,105 / 1,Hla,70 / 6,Mya / 7,Nu Nu,64

  • Skip the header (line 1) and blank lines without counting them as skipped
  • Split three fields with std::getline(fields, x, ',') and reject a line with a missing field
  • Check the pos argument of std::stoi / std::stod and reject text that is not entirely a number
  • Reject out-of-range marks and duplicate rolls, and return the added/skipped counts
  • Write the CSV into the temp directory, read it through std::ifstream, then delete the file
challenge.cpp
// Reuse Student and StudentManager (add, sortByMarks, displayAll) from the lesson.

struct ImportResult {
    std::size_t added = 0;
    std::size_t skipped = 0;
};

// TODO: convert the WHOLE text with std::stoi(text, &used).
//       Throw std::invalid_argument if stoi throws, or if used != text.size().
int parseRoll(const std::string& text);

// TODO: same idea with std::stod, so "88x" is rejected instead of read as 88.
double parseMarks(const std::string& text);

ImportResult importCsv(std::istream& in, StudentManager& manager) {
    ImportResult result;
    // TODO: read line by line with std::getline; skip line 1 (header) and blanks
    // TODO: split each line into roll, name, marks with std::getline(fields, x, ',')
    // TODO: build the Student, reject duplicate rolls, count added / skipped,
    //       and print "line N: <reason>" for every skipped line
    return result;
}

int main() {
    // TODO: write the CSV text from the brief to a unique file in
    //       std::filesystem::temp_directory_path()
    // TODO: import it through an std::ifstream, delete the file,
    //       print "Added A, skipped S", then sort and display the students
}

Expected: Five error lines for lines 5, 6, 7, 8 and 9, then "Added 3, skipped 5", then a table sorted by marks: Bo (91.0), Aye Aye (78.5), Nu Nu (64.0).

Show hint

std::stod("88x", &used) returns 88 and sets used to 2, so reject the line when used != text.size(). The exceptions stoi and stod throw have unhelpful what() text (often just "stoi"), so throw your own invalid_argument with a clear message.

Show solution
challenge.cpp
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

namespace fs = std::filesystem;

class Student {
public:
    Student(std::string name, int roll, double marks)
        : name_(std::move(name)), roll_(roll), marks_(checkedMarks(marks)) {}

    const std::string& getName() const { return name_; }
    int getRoll() const { return roll_; }
    double getMarks() const { return marks_; }

private:
    static double checkedMarks(double marks) {
        if (marks < 0.0 || marks > 100.0) {
            throw std::invalid_argument("marks must be between 0 and 100");
        }
        return marks;
    }

    std::string name_;
    int roll_;
    double marks_;
};

class StudentManager {
public:
    bool add(const Student& student) {
        for (const Student& s : students_) {
            if (s.getRoll() == student.getRoll()) {
                return false;
            }
        }
        students_.push_back(student);
        return true;
    }

    void sortByMarks() {
        std::sort(students_.begin(), students_.end(),
                  [](const Student& a, const Student& b) {
                      if (a.getMarks() != b.getMarks()) {
                          return a.getMarks() > b.getMarks();
                      }
                      return a.getRoll() < b.getRoll();
                  });
    }

    void displayAll() const {
        std::cout << "Roll  Name     Marks\n";
        for (const Student& s : students_) {
            std::cout << std::format("{:>4}  {:<8}{:>6.1f}\n",
                                     s.getRoll(), s.getName(), s.getMarks());
        }
    }

private:
    std::vector<Student> students_;
};

struct ImportResult {
    std::size_t added = 0;
    std::size_t skipped = 0;
};

// The whole text must be a number: "88x" and "" are errors, not 88 and 0.
int parseRoll(const std::string& text) {
    std::size_t used = 0;
    int value = 0;
    try {
        value = std::stoi(text, &used);
    } catch (const std::exception&) {  // invalid_argument or out_of_range
        used = 0;
    }
    if (used == 0 || used != text.size()) {
        throw std::invalid_argument(std::format("'{}' is not a whole number", text));
    }
    return value;
}

double parseMarks(const std::string& text) {
    std::size_t used = 0;
    double value = 0.0;
    try {
        value = std::stod(text, &used);
    } catch (const std::exception&) {
        used = 0;
    }
    if (used == 0 || used != text.size()) {
        throw std::invalid_argument(std::format("'{}' is not a number", text));
    }
    return value;
}

ImportResult importCsv(std::istream& in, StudentManager& manager) {
    ImportResult result;
    std::string line;
    int lineNo = 0;
    while (std::getline(in, line)) {
        ++lineNo;
        if (lineNo == 1 || line.empty()) {
            continue;  // header row or blank line
        }
        std::istringstream fields(line);
        std::string rollText, name, marksText;
        try {
            const bool complete = std::getline(fields, rollText, ',') &&
                                  std::getline(fields, name, ',') &&
                                  std::getline(fields, marksText);
            if (!complete) {
                throw std::invalid_argument("a field is missing");
            }
            const int roll = parseRoll(rollText);
            if (!manager.add(Student(name, roll, parseMarks(marksText)))) {
                throw std::invalid_argument(std::format("roll {} already exists", roll));
            }
            ++result.added;
        } catch (const std::invalid_argument& e) {
            std::cout << std::format("line {}: {}\n", lineNo, e.what());
            ++result.skipped;
        }
    }
    return result;
}

int main() {
    auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
    const fs::path csv = fs::temp_directory_path() / std::format("import-{}.csv", stamp);
    {
        std::ofstream out(csv);
        out << "roll,name,marks\n1,Aye Aye,78.5\n2,Bo,91\n\n3,Chit,abc\n"
               "4,Daw,88x\n5,Ei,105\n1,Hla,70\n6,Mya\n7,Nu Nu,64\n";
    }

    StudentManager manager;
    std::ifstream in(csv);
    const ImportResult result = importCsv(in, manager);
    in.close();
    fs::remove(csv);

    std::cout << std::format("Added {}, skipped {}\n", result.added, result.skipped);
    manager.sortByMarks();
    manager.displayAll();
}

Quick quiz 1 / 3

After in >> marks fails on "abc", what lets the next command be read?

Quick quiz 2 / 3

Why does the comparator compare roll numbers when the marks are equal?

Quick quiz 3 / 3

The data file contains the line "5 64 Ei Mon". What does loadFromFile() store?

What to remember

  • Catch exceptions in the code that talks to the user, report what went wrong and carry on
  • After a failed read, call clear() and then ignore() to make the stream usable again
  • A std::sort comparator must be strict (> or <) and needs a second key for ties
  • Save one record per line with free text last, and validate again when loading

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Mini Project: Student Manager - Part 3 | Thuta Learning