Skip to main content
gamedev.net
🔒 Locked

Read Line into stringstream.rdbuf()

Started by Boder 1 reply 1.2k views
Original Post
Boder
Boder
Why does the input fail when passing the string buffer of a string stream into the get() method for an ifstream?

#include <sstream>
#include <fstream>
#include <iostream>
#include <cassert>

using namespace std;

char const * const text =
"This text is const \n\nconst for you and const for me. \n\nDo you like const text? \n\nI do.\n";

int main()
{

 ofstream out("text.txt");
 out << text;
 out.close();

 ifstream in("text.txt");
 stringstream buffer;

 while( !in.eof() )
 {

  in.get( *buffer.rdbuf() );
  cout << buffer.str() << endl;
  assert( in.good() );

 }

 in.close();

}

Bregma
Bregma
The std::istream.get() function does not consume the delimiter, so the next iteration through the loop it copies nothing from the input buffer to the output buffer. Not copying anything sets the input buffer into an error state.

The default delimiter is newline.

This is a pretty obscure function to use in application code. You may find there is a reason why you don't generally see it used.
Stephen M. Webb
Professional Free Software Developer
Boder
Boder
I kind of got it to work. Thanks for the tip.

while( !in.eof() && in.good() ){ while( in.peek() == '\n' ) in.get(); in.get( *buffer.rdbuf() ); cout << buffer.str() << endl; buffer.str("");}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.