That code is essentially C.
You have two things that should be kept separate: the echo and the true nature of the streams.
Lets do echo:
1 2 3 4 5 6 7
|
void echo( std::istream & in, std::ostream & out ) {
std::string word;
while ( /*read from in into word*/ ) {
/*write word into out*/
out << '\n';
}
}
|
The code that you should put there instead of the comments uses operator>> and operator<<.
Why have a fancy function. What to do with it?
1 2 3 4 5 6 7 8 9 10
|
int main( int argc, char* argv[] ) {
if ( 2 <= argc ) {
std::ifstream fin( argv[1] );
echo( fin, std::cout );
}
else {
echo( std::cin, std::cout );
}
return 0;
}
|
What does that do? If you give at least one command line argument, when running the program, the first argument is used as name of the input file. If run without arguments, the std::cin is used. In both cases the output goes to std::cout.
Therefore, either of these would be ok:
a.out < example.txt > result.txt
a.out example.txt > result.txt |
You could, obviously, go one step further and make the program use two arguments, one for input and the other for output filename.
The above code depends on
1 2 3
|
#include <iostream>
#include <fstream>
#include <string>
|