At first glance, the simplest solution would be to use the ternary operator ?: As follows:
istream_iterator<string> my_it( (argc == 2) ? ifstream(argv[1]) : cin );
However, this will not work because it creates a temporary ifstream object that will be destroyed at the end of the statement. So you need a way to conditionally create an ifstream and conditionally destroy it after the for loop. std::auto_ptr<> matches the count. Thus:
auto_ptr<ifstream> file((argc == 2) ? new ifstream(argv[1]) : NULL); istream_iterator<string> my_it( (argc == 2) : *file : cin); for (; my_it != istream_iterator<string>(); my_it++) printf("%s\n", (*my_it).c_str());
Another, possibly cleaner solution, is to move the iteration into a separate function that accepts istream& .
I saw this problem before it was online, which is covered by one of the great C ++. Unfortunately, I donβt remember exactly where, or by whom! I think it was on DDJ, maybe Sutter or Alexandrescu?
source share