I like @Martin R's solution.
For this specific situation it is the best.
The code I present below is for learning purposes and shows a simple technique for converting input from one format to another. The technique is useful (but needs a a slightly more complex problem before it is worth using). But this problem provides a simple enough problem that understanding it becomes trivial.
#include <algorithm>
#include <iterator>
#include <utility>
#include <string>
#include <iostream>
#include <fstream>
// Define a structure for reading the input with.
// Including the input operator<<
struct Line
{
std::string line;
friend std::istream& operator>>(std::istream& str, Line& data)
{
return std::getline(str, data.line);
}
};
// Define a structure that takes an
// input record and converts it to the format you want to use for output.
// Including the output operator>>
struct LineAppend
{
static std::string append;
std::string line;
LineAppend(Line const& inputLine)
: line(inputLine.line)
{}
friend std::ostream& operator<<(std::ostream& str, LineAppend const& data)
{
return str << data.line << append << "\n";
}
};
// Slightly hacky for this example
std::string LineAppend::append;
The transformation then simply becomes a copy.
int main(int argc, char* argv[])
{
std::ifstream input(argv[1]);
LineAppend::append = argv[2];
// Now copy the input to the output.
std::copy(std::istream_iterator<Line>(input),
std::istream_iterator<Line>(),
std::ostream_iterator<LineAppend>(std::cout, "\n"));
}
Now moving to C++11 we can use the range based for:
// Define a class that can be used as range based container.
// This just means defining begin() and end() appropriately.
template<typename T>
class StreamReader
{
std::istream& str;
public:
StreamReader(std::istream& str)
: str(str)
{}
std::istream_iterator<T> begin() {return std::istream_iterator<T>(str);}
std::istream_iterator<T> end() {return std::istream_iterator<T>();}
std::istream_iterator<T const> begin() const {return std::istream_iterator<T>(str);}
std::istream_iterator<T const> end() const {return std::istream_iterator<T>();}
};
int main()
{
std::ifstream input(argv[1]);
for(Line const& line : StreamReader<Line>(input))
{
std::cout << line.line << argv[2] << "\n";
}
}