Write a C++ program that implements flipping the contents of each line of a string in a text file and outputs the flipped result to another text file. Both the input file name and output file name are specified by the user.
时间: 2024-03-01 13:52:19 浏览: 24
Sure, here's an implementation of the program you described:
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
int main()
{
std::string input_filename, output_filename;
std::cout << "Enter input file name: ";
std::cin >> input_filename;
std::cout << "Enter output file name: ";
std::cin >> output_filename;
std::ifstream input_file(input_filename);
if (!input_file.is_open())
{
std::cerr << "Failed to open input file: " << input_filename << std::endl;
return 1;
}
std::ofstream output_file(output_filename);
if (!output_file.is_open())
{
std::cerr << "Failed to open output file: " << output_filename << std::endl;
return 1;
}
std::string line;
while (std::getline(input_file, line))
{
std::reverse(line.begin(), line.end());
output_file << line << std::endl;
}
std::cout << "Done!" << std::endl;
return 0;
}
```
Here's how it works:
1. The user is prompted to enter the input and output file names.
2. The program attempts to open the input and output files for reading and writing, respectively. If either operation fails, an error message is printed and the program exits with an error code.
3. The program reads each line from the input file, reverses the order of its characters, and writes the result to the output file.
4. When all lines have been processed, the program prints a "Done!" message and exits with a success code.
Note that this implementation assumes that the input file exists and is readable, and that the output file can be created or overwritten as needed. It also assumes that each line in the input file is terminated by a newline character, and that the output file should have the same newline format. If these assumptions do not hold, the program may produce unexpected results.
阅读全文