← C++ from Scratch Lesson 45 of 62 · 10 XP

Files: fstream

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

<fstream> provides streams for files — they work just like std::cout and std::cin:

std::ofstream out("save.txt");     // open for writing (the file is created or overwritten)
out << "level 3\n" << "hp 80\n";
out.close();

std::ifstream in("save.txt");      // open for reading
if (!in) { std::cout << "no file\n"; }
std::string key;
int value;
while (in >> key >> value) { … }   // read pairs until the end of the file

std::ofstream log("log.txt", std::ios::app);   // append to the end

A stream closes by itself when the object goes out of scope (RAII). In the browser the program has its own file system in memory — the files live while the program is running.

Task. Read n lines of name score from the console. Write them to the file scores.txt. Then open the file again for reading, read the records and print the best player and the total score of all players: best: <name> <score> and sum: <total>.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.