Reputation: 47620
If there is argv[1]
I want to put some data to new ofstream(argv[1])
i.e file with name argv[1]
. But if there are no such argument I want to use cout
instead.
I've tried
std::ostream& output = argc >= 1 ? std::fstream(argv[0]) : std::cout;
But it even doesn't compile because of deleted constructor.
Upvotes: 3
Views: 418
Reputation: 58471
Here is a truly C++11 solution:
ostream& out = [=]() -> ostream& {
if (argc>1) {
static fstream fs(argv[1]);
return fs;
}
return cout;
}();
Upvotes: 3
Reputation: 92271
You cannot use a ternary operator with different types. The compiler cannot decide what type the result should have.
You could try
if (argc >= 1)
{
std::fstream Output(argv[0]);
Process_data(Output);
}
else
Process_data(std::cout);
Upvotes: 2
Reputation: 4034
You can create an fstream instance and delay opening it until necessary.
std::fstream file;
if (argc > 1)
file.open(argv[1]);
std::ostream& output = argc > 1 ? file : std::cout;
Upvotes: 6