1

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;
Tom Pažourek
  • 9,582
  • 8
  • 66
  • 107

2 Answers2

0

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.

Community
  • 1
  • 1
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
0

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;
}
Nim
  • 33,299
  • 2
  • 62
  • 101
  • 1
    You are reading words, not lines. End of stream can easily be tested without a prior knowlege of line count. Just use void*operator. – Basilevs Nov 26 '10 at 03:20