Question

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;
Was it helpful?

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;
}

OTHER TIPS

There is detailed info in the question below (per @Martin York) on reading direct from stream to stringstream. This is not a direct dup as you wish to handle the input line by line, but this approach will be hard to beat for efficiency. You can instantiate the individual lines using a character range once the raw data is in the stringstream.

How to read file content into istringstream?

To be honest, this may be a lot of work for a problem that's not really a huge perf concern anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top