Question 10
Back to Exercise
Read all lines of a file into a vector, write them in reverse order with line numbers to a new file using std::format-style padding, and print the new file.
Solution
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main() {
auto dir = std::filesystem::temp_directory_path();
std::ofstream(dir / "lf_steps.txt") << "wake up\nbrush\nbreakfast\nstudy C++\nsleep\n";
std::vector<std::string> lines;
{
std::ifstream in(dir / "lf_steps.txt");
for (std::string l; std::getline(in, l); ) lines.push_back(l);
}
{
std::ofstream out(dir / "lf_reversed.txt");
for (std::size_t i = lines.size(); i-- > 0; )
out << std::format("{:>2}. {}\n", lines.size() - i, lines[i]);
}
std::ifstream r(dir / "lf_reversed.txt");
std::cout << r.rdbuf();
r.close();
std::filesystem::remove(dir / "lf_steps.txt");
std::filesystem::remove(dir / "lf_reversed.txt");
return 0;
}
1. sleep 2. study C++ 3. breakfast 4. brush 5. wake up
Text files can only be read forwards line by line, so the lines are collected first. The loop i-- > 0 counts down safely with an unsigned index.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!