← Back to Streams
Question 620
High Scores Save and Load
High Scores Save and Load
Create a classHighScoresthat 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: opensfilenamewith anofstream(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): opensfilenamewith anifstream. If it cannot be opened, returnfalseand leave the list unchanged. Otherwise clear the list, read every name/score pair in file order, and returntrue. 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), callssave("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), thenloads a file containingCal 70andDee 95; it printsloaded(orload failed) and callsprint(). It then callsload("missing_dir/highscores.txt"), printsloadedorload failedagain, and callsprint()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
Sign in to use hintsTopics:
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.