CJCoding With Joseph
15free / daySign inCreate account

High Scores Save and Load

Create a class HighScores that keeps a list of (name, score) entries.

1. void add(const string& name, int score): appends an entry.
2. void save(const string& filename) const: opens filename with an ofstream (truncating) and writes the entries sorted by score, highest first, one per line as the name, a space, the score. Sort a copy — the stored order must not change. All scores are different.
3. bool load(const string& filename): opens filename with an ifstream. If it cannot be opened, return false and leave the list unchanged. Otherwise clear the list, read every name/score pair in file order, and return true.
4. void print() const: prints every entry in stored order, one per line as the name, a space, the score.

Test 1 adds ("Amy", 85) then ("Bob", 90), calls save("highscores_a.txt") on a file that already holds an old line, then reopens the file and prints every line (see Expected Output).

Test 2 adds ("Zed", 1), then loads a file containing Cal 70 and Dee 95; it prints loaded (or load failed) and calls print(). It then calls load("missing_dir/highscores.txt"), prints loaded or load failed again, and calls print() again:
loaded
Cal 70
Dee 95
load failed
Cal 70
Dee 95

Do NOT write a main function.

Expected Output:

Bob 90
Amy 85
loaded
Cal 70
Dee 95
load failed
Cal 70
Dee 95

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Streamsofstream
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.