Search code examples
c++streamiostreamstringstreamistream

Read 1 line from istream to string stream without temporary variable in C++?


Is is possible to read one line from input stream and pass it to string stream without using temorary string variable in C++?

I currently do the reading like this (but I don't like the temporary variable line):

string line;
getline(in, line); // in is input stream
stringstream str;
str << line;

Solution

  • Like @Steve Townsend said above, it's probably not worth the effort, however if you wanted to do this (and you knew beforehand the number of lines involved), you could do something like:

    #include <iostream>
    #include <iterator>
    #include <string>
    #include <sstream>
    #include <algorithm>
    
    using namespace std;
    
    template <typename _t, int _count>
    struct ftor
    {
      ftor(istream& str) : _str(str), _c() {}
    
      _t operator() ()
      { 
        ++_c;
        if (_count > _c) return *(_str++); // need more
        return *_str; // last one
      }
    
      istream_iterator<_t> _str;
      int _c;
    };
    
    int main(void)
    {
      ostringstream sv;
      generate_n(ostream_iterator<string>(sv, "\n"), 5, ftor<string, 5>(cin));
    
      cout << sv.str();
    
      return 0;
    }