I have a problem with I/O streams in C++. I have to write a program which reads data from a file and writes to another file. The command in CMD should be like:
program < file1 > file2
The names of the files should be provided by the user (could be random).
I've written some code, but it's not correct. I don't know how to redirect the stream to a file using the command > file2.
What can I change in my code to make it work? Can somebody help me?
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string input_line;
while (std::getline(std::cin, input_line)) {
std::ofstream output_file("file2.txt", std::ios::app);
if (!output_file.is_open()) {
std::cerr << "Error" << std::endl;
return 1;
}
output_file << input_line << std::endl;
output_file.close();
}
return 0;
}
OK.
This implies you are using the shell to do the work. Here. The
<and>are shell "operators" to redirect files to standard in and standard out of the program. This means your program should read fromstd::cinand write tostd::cout.You assume the output file is "file2.txt"!
You are always appending to it. If the file already exists, this may not be what you want, as it will add the new content onto any old content. I would probably change that (if I was using files). But the simpler solution is to use
std::cout(as indicated above).I am assuming you are doing this as part of an exercise, so going through the steps.
If I was writing this for a class that was trying to understand streams. This is how I would re-write more like this:
Note: This is not quite perfect as the last line may not include a new line character, but the code above always add a newline to every line. I leave it as an exercise for you to solve this last simple issue.